views:

1446

answers:

2

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.

+2  A: 

Actively killing the thread:

Use the return value of AfxBeginThread (CWinThread*) to get the thread handle (m_hThread) then pass that handle to the TerminateThread Win32 API. This is not a safe way to terminate threads though, so please read on.

Waiting for the thread to finish:

Use the return value of AfxBeginThread (CWinThread*) to get the member m_hThread, then use WaitForSingleObject(p->m_hThread, INFINITE); If this function returns WAIT_OBJECT_0, then the thread is finished. Instead of INFINITE you could also put the number of milliseconds to wait before a timeout happens. In this case WAIT_TIMEOUT will be returned.

Signaling to your thread that it should end:

Before doing the WaitForSingleObject just set some kind of flag that the thread should exit. Then in your main loop of the thread you would check for that bool value and break the infinite loop. In your destructor you would set this flag then do a WaitForSingleObject.

Even better ways:

If you need even more control you can use something like boost conditions.

Brian R. Bondy
A: 

You must wait, until thread do all stuff.

if(WaitForSingleObject(thread_handle, INFINITE) == WAIT_OBJECT_0) 
    ;//all right
else
    ;//report error

beware using TerminateThread function, this is very dangerous.

Lazin