Windows 線程間訊息通訊

來源:互聯網
上載者:User

標籤:線程   通訊   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 線程間訊息通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.