I have an application which second thread calls GetMessage()
in a loop. At some point the first thread realizes that the user wants to quit the application and notifies the second thread that it should terminate. As the second thread is stuck on GetMessage()
, the program never quits. Is there a way to wait for messages with a timeout?
I’m open to other ideas too.
EDIT: (additional explanations)
The second thread runs that snippet of code:
while ( !m_quit && GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
The first thread sets m_quit
to true.
Not tested, but you could try the function MsgWaitForMultipleObjects without actually any object.
MsgWaitForMultipleObjects(0, NULL, FALSE, timeout, QS_ALLINPUT);
If if returns WAIT_TIMEOUT
it is a timeout, but if it returns WAIT_OBJECT_0
you can call GetMessage
with guarantee not to be blocked.
But note the following:
MsgWaitForMultipleObjects does not return if there is unread input of the specified type in the message queue after the thread has called a function to check the queue.
So you have to ensure that the last time you called any of the message functions there is no messages left on the queue, or you will have a kind of race condition.
Probably your best option would be to replace GetMessage
with:
if (MsgWaitForMultipleObjects(0, NULL, FALSE, timeout, QS_ALLINPUT) == WAIT_OBJECT_0)
{
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
//dispatch the message
}
}
But as I said before, I didn't test it so I cannot be sure if it will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With