Using CEvent / CWinthread during thread termination
Posted on 2005-05-17
I'm writing a multithreaded MFC application (famous last words, I know). I have a main dialog based application that uses AfxBeginThread to launch a CWinthread-derived UI thread of my design. My question relates to how to properly terminate the thread when someone presses the cancel button in the main application dialog.
What I've tried so far is the following: I created a CEvent member variable within the CWinthread-derived class which I initially set to unsignalled. I have overridden OnCancel in the main dialog as follows:
m_pMyThread->PostThreadMessage(WM_BAILOUT, 0, 0);
When I catch the WM_BAILOUT message in my thread, I call PostQuitMessage. Then, in ExitInstance for the thread, I have:
This all seems to work just as I expect, but my question is this: Is there a possibility that after the event is signalled, my thread will finish terminating and get deleted before the calling thread (my dialog app) has a chance to properly "see" the event when it's still valid. In other words, am I running the risk of some later timing issues having it hang indefinitely? Is this the correct and thread-safe way to do things? The documentation for MFC's synchronization classes seems spotty to me and I'm not sure if they have some internal mechanisms for making sure things like this function correctly (in fact, I don't see how it could).
Any help would be greatly appreciated.