Messaging Between Threads, Exiting Thread On Demand, Etc.
Good afternoon everyone.... Just had a few questions regarding threads if someone wouldn't mind answering.
I have a main thread (GUI Thread), which creates a secondary thread for processing. There are many times that I want the main thread to signal to the secondary thread to stop and exit immediately. Currently I'm using a global boolean to do this and in the secondary thread periodically checking and then calling ExitThread ( ). I'm really not a big fan of this and depending what part in the secondary thread that is being executed there is not a prompt exit.
I basically want to set up a message scheme between the two threads so that the main can "PostThreadMessage(WM_EXIT_NOW)" and the secondary thread will check its message queue and then call ExitThread() from there. This would be nice as I could also communicate other things. Is this possible? Below is what I've tried, but the secondary thread never appears to receive a message.
This is global.
This is the main thread.
secondaryThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID);
PostThreadMessage(threadID, WM_USER + 5, 1, 1);
I don't know... I tried to set up a message queue in the secondary thread. Set a hook to catch all incoming messages, and then attempt to process that message, but I never get into the HOOK function.
PeekMessage(&msg, NULL, WM_USER, WM_USER + 40, PM_NOREMOVE);
hook = SetWindowsHookEx(WH_GETMESSAGE, &GetMsgProc, NULL, threadID);
LRESULT CALLBACK GetMsgProc(int code, WPARAM wParam, LPARAM lParam)
Any ideas? Any better approach to this problem?
P.S. The PeekMessage() line I got from MSDN
PSS: Also, I am positive the secondary thread has not finished executing before the PostThreadMessage() has been sent.
Create an event object, then create the thread. Use the WaitForSingleObject
function to wait for the event to be set to the signaled state before calling PostThreadMessage
. In the thread to which the message will be posted, call PeekMessage
as shown here to force the system to create the message queue.