Alex Rivera | Logout

How to kill a MFC Thread?

Asked 2009-02-26T14:33:26.803
11

I spawn a thread using AfxBeginThread which is just an infinite while loop:

UINT CMyClass::ThreadProc( LPVOID param )
{
  while (TRUE)
  {
      // do stuff
  }
  return 1;
}

How do I kill off this thread in my class destructor?

I think something like

UINT CMyClass::ThreadProc( LPVOID param )
{
  while (m_bKillThread)
  {
      // do stuff
  }
  return 1;
}

and then set m_bKillThread to FALSE in the destructor. But I still need to wait in the destructor until the thread is dead.

Edit
Report

1 Answer

6

BTW, About TerminateThread(), use it this way.

DWORD exit_code= NULL;
if (thread != NULL)
{
    GetExitCodeThread(thread->m_hThread, &exit_code);
    if(exit_code == STILL_ACTIVE)
    {
        ::TerminateThread(thread->m_hThread, 0);
        CloseHandle(thread->m_hThread);
    }
    thread->m_hThread = NULL;
    thread = NULL;
}
answered 2012-02-25T13:39:38.707

Your Answer