Link to home
Start Free TrialLog in
Avatar of jymmealey
jymmealey

asked on

How to test if a thread has ended

Hello all,

     I have a CWinThread derived class that I am using.  Occationally while the thread is running I will post it thread messages using PostThreadMessage() which works fine.  The object is deleted when the threads finishes the Run() function because I have set m_bAutoDelete = TRUE.  However, if the thread ends before I expected it to, I get an error because I am trying to PostThreadMessage to an object that no longer exists.

    How can I test to see if PostThreadMessage is going to cause an error because the object is deleted?

Thanks
Avatar of jymmealey
jymmealey

ASKER

Here is a some code to explain what I am talking about

m_pPingThread = (Ping_Thread*) AfxBeginThread(RUNTIME_CLASS(Ping_Thread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
m_pPingThread->ResumeThread();

while (true) {
     m_pPingThread->PostThreadMessage(WM_USER + 1, 0, 0);
     Sleep(1000);
}

Once the "Ping_Thread" ends I will get an error trying to post at thread message
Avatar of jkr
You could use

DWORD dw;
GetExitCodeThread(m_pPingThread->m_hThread, &dw);

if ( STILL_ACTIVE == dw) {

// still running
}
Won't that still error because I am still trying to access the member of a deleted object?
Sorry, that's of course correct. Do you really net to set it to ''AutoDelete'? I.e.

while (true) {
    DWORD dw;
    GetExitCodeThread(m_pPingThread->m_hThread, &dw);

    if ( STILL_ACTIVE == dw) {

      // still running
    m_pPingThread->PostThreadMessage(WM_USER + 1, 0, 0);

    } else {

        m_pPingThread = NULL;

        break;
    }

    Sleep(1000);
}

would seem a lot 'healthier' to me (the above assumes 'm_bAutoDelete == FALSE')
I don't have to but how do I get the object to delete after I am done with it?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried that but I am getting a complier error saying
error C2248: 'Ping_Thread::~Ping_Thread' : cannot access protected member declared in class 'Ping_Thread'

Do I just need to move the desctructor to a private rather than protected?

>>Do I just need to move the desctructor to a private rather than protected?

No, better move it to the 'public:' section.