Using a message is one of the common ways that threads see communication. Windows also provides a number of functions to achieve this. The main functions used are postthreadmessage (), PeekMessage (), GetMessage ()
Send message:
General messages are associated with Windows (window). For threads without Windows, Windows provides a special message function, PostThreadMessage (). This function replaces the window handle parameter in PostMessage () with the target thread ID. Thread ID can be passed through parameters during threads creation, or the ID of the current thread can be obtained with the GetCurrentThreadID () function
A message queue is required for a thread to receive a message, and by default it does not have a message queue. Thread Message Queuing can be created using PeekMessage (&msg,null, Wm_user, Wm_user, Pm_noremove) in the target thread
Receive Message:
Message reception can be one of two functions with PeekMessage () and GetMessage (). The difference between the two functions is that getmessage () is not returned immediately and waits until the message is received. PeekMessage () No message will return immediately. The difference is literally well understood, and peek is the meaning of a glance.
Message content
Message content can be passed by PostThreadMessage () after two parameters wparam and lparam. WPARAM is unsigned, LPARAM is signed, and two parameters can pass pointers.
code example:
Send message:
msg msg; BOOL status; Msg.hwnd = NULL; Msg.message = Wm_user; Msg.wparam = (wParam) _mode; if (! PostThreadMessage (Mmainthreadid, Wm_user, (WPARAM) _para, NULL)) { trddiags::instance (). Diagsprint ( Trddiags::flags_timestamp, 0, nullptr, __function__, "PostThreadMessage failed!"); return false; } End of--if (! PostThreadMessage (Mmainthreadid, Wm_user, (WPARAM) _para, NULL))
Receive in Mainthread:
unsigned int runmainthread (void) { msg msg; Custom_type para; Mmainthreadid = GetCurrentThreadID (); PeekMessage (&msg, NULL, Wm_user, Wm_user, pm_noremove); Create message queue for current thread bool running = true; while (running) {while (PeekMessage (&msg, NULL, 0, 0, pm_remove)) { switch (msg.message) {case wm_user: mode = (MODES) Msg.wparam; Handlemessage (); Handle messages base on different wParam break ; Default: Break, }//End of--switch (msg.message) } //End of--while (PeekMessage (&msg, null,< c23/>0, 0, Pm_remove) }//End of--while (running) return (0);}
Reference:
Http://www.codeproject.com/Articles/225755/PostThreadMessage-Demystified
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644928 (v=vs.85). aspx
Windows inter-thread message communication