Friday, December 16, 2005

How to properly terminate a thread.

The terminating of a thread is a pretty tricky issue, basically, you should never call terminating thread explicitly.

The spawned thread normally runs in Run() method, where it will wait for some shutdown event. In the main thread, when it determeines that the main thread should be terminated, it should set that event, and then wait on the thread handle for it to complete.

void CMainClass::InitiateShutdown()
{
//do some cleaning work.
m_shutdownEvent.Set();
}

After the thread catches that event, it should exits the loop.

And in another Wait() function, the main thread should waits on the Run() to finishe by waiting on that thread object like this:

DWORD result = ::WaitForSingleObject(m_hThread, timeoutMillis);

Then the main thread will be able to exit.

No comments: