標籤:線程 通訊 windows message
使用訊息(message)是線程見通訊的常用方法之一。Windows也提供了許多函數來實現這一點。主要使用的函數有PostThreadMessage(), PeekMessage(), GetMessage()
發訊息:
一般訊息都是和視窗(window)聯絡在一起的。對於沒有視窗的線程, windows提供了專門的發訊息函數PostThreadMessage()。 該函數把PostMessage()裡的視窗控制代碼參數換成了目標線程ID。線程ID線上程建立過程中可以通過參數傳遞出來,也可以用GetCurrentThreadId()函數擷取當前線程的ID
線程需要接收訊息的話需要有個訊息佇列,預設是不具有訊息佇列的。在目標線程裡使用PeekMessage(&msg,NULL, WM_USER, WM_USER, PM_NOREMOVE) 就可以建立線程訊息佇列
接收訊息:
訊息接收可以用PeekMessage()和GetMessage()兩個函數之一。兩個函數的區別是GetMessage()不是立即返回,在接收到訊息之前一直等待。PeekMessage()沒有訊息也會立即返回。這個差別從字面也很好理解,peek是瞅一眼的意思。
訊息內容
訊息內容可以通過PostThreadMessage()後兩個參數wParam和lParam來傳遞。wParam是無符號的,lParam是有符號的,兩個參數都可以傳遞指標。
代碼範例:
發送訊息:
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))
在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, 0, 0, PM_REMOVE)) } // end of -- while (running) return (0);}
參考:
http://www.codeproject.com/Articles/225755/PostThreadMessage-Demystified
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644928(v=vs.85).aspx
Windows 線程間訊息通訊