Programming Tips - Win32: the best way to communicate something to a thread

Date: 1997dec15 Updated: 2020oct11 Platform: win32 Language: C/C++ Q. Win32: the best way to communicate something to a thread from another thread. And what if you want to queue some messages? A. Use PostThreadMessage() to queue a message. Better than Mutexs and Semaphores. The thread needs to have a PeekMessage() loop. Here's what the manual says: The PostThreadMessage function places (posts) a message in the message queue of the specified thread and then returns without waiting for the thread to process the message.
BOOL PostThreadMessage( DWORD idThread, // thread identifier UINT Msg, // message to post (nearly always WM_USER or WM_APP - dave) WPARAM wParam, // first message parameter LPARAM lParam // second message parameter );
The thread can do this while not busy:
DWORD SleepWhileQueueEmpty(const DWORD dwMilliSeconds) { return MsgWaitForMultipleObjectsEx(0, NULL, dwMilliSeconds, QS_ALLINPUT, MWMO_INPUTAVAILABLE); }