使用PostThreadMessage向工作線程發送消息

window線程間傳送消息仔細的看了一遍,覺得以前的理解很不深刻。說一說對PostThreadMessage的理解。

 

PostThreadMessage是一個線程體發送一個消息到指定的線程ID,其原型如下:

 

BOOL PostThreadMessage(         

                    DWORD idThread,

                    UINT Msg,  

                    WPARAM wParam,   

                    LPARAM lParam

);

       這個函數既可以發送消息給工作線程,也可以發送給UI線程。接受PostThreadMessage的線程必須已經有了一個message queue,否則調用PostThreadMessage會失敗。因爲此原因使用GetLastError會得到錯誤碼爲1444,這種情況經常出現,解決方法有如下兩種:

 

1.         調用PostThreadMessage,如果失敗,就Sleep一段時間再次調用PostThreadMessage直到調用成功;

 

2.         創建一個Event對象,讓PostThreadMessage等待接受的線程創建一個message queue。可以通過調用PeekMessage強制系統創建一個message queue。示例代碼如下:

 

 

 

假設mainAPP是發送線程ThreadA是接受線程

 

/*mainAPP.cpp*/

……

hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event

if(hStartEvent == 0)

{

          printf("create start event failed,errno:%d/n",::GetLastError());

          return 1;

}

::WaitForSingleObject(hStartEvent,INFINITE);

CloseHandle(hStartEvent);

if(!PostThreadMessage(threadaID, WM_MESSAGE_A,0,0))

{

          _tprintf(_T("post error! %d/n"), GetLastError());

          return 1;

}

……

ThreadA是接受線程

 

/* ThreadA */

MSG msg;

PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

if(!SetEvent(hStartEvent))

{

          printf("set event error,%d/n",GetLastError());

          return 1;

}

while(true){

          if(GetMessage(&msg, 0,0,0)) {

                    switch(msg.message){

                              case WM_MESSAGE_A:

                               ……

                               break;

                              }

                    }

          }

}

PostThreadMessage傳遞的消息如果要包含信息,要注意在結束的時候釋放消息中的信息。在消息中附加信息方法如下

 

/*構造信息如下*/

char* pInfo = new char[MAX_INFO_SIZE]; //create dynamic msg

sprintf(pInfo,"msg_%d",++count);

PostThreadMessage(nThreadID,MY_MSG,(WPARAM)pInfo,0)//post thread msg

 

/*解釋信息如下*/

if(GetMessage(&msg,0,0,0)) //get msg from message queue

{

            switch(msg.message)

            {

            case MY_MSG:

            char * pInfo = (char *)msg.wParam;

            printf("recv %s/n",pInfo);

            delete[] pInfo; //這裏釋放了資源

            break;

            }

}

做了一個簡單的消息通信實驗,讓主線程中等待用戶輸入,產生不同的消息,並把這些消息post給子線程,子線程根據產生的消息做出不同的反映。這些子線程可以是工作線程也可以是UI線程。

 

 

 

 

 

#include <windows.h>

#include <cstdio>

#include <process.h>

 

#define MY_MSG WM_USER+100

const int MAX_INFO_SIZE = 20;

 

HANDLE hStartEvent; // thread start event

 

// thread function

unsigned __stdcall fun(void *param)

{

    printf("thread fun start/n");

 

    MSG msg;

    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

 

    if(!SetEvent(hStartEvent)) //set thread start event

    {

        printf("set start event failed,errno:%d/n",::GetLastError());

        return 1;

    }

   

    while(true)

    {

        if(GetMessage(&msg,0,0,0)) //get msg from message queue

        {

            switch(msg.message)

            {

            case MY_MSG:

                char * pInfo = (char *)msg.wParam;

                printf("recv %s/n",pInfo);

                delete[] pInfo;

                break;

            }

        }

    };

    return 0;

}

 

int main()

{

    HANDLE hThread;

    unsigned nThreadID;

 

    hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event

    if(hStartEvent == 0)

    {

        printf("create start event failed,errno:%d/n",::GetLastError());

        return 1;

    }

 

    //start thread

    hThread = (HANDLE)_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID );

    if(hThread == 0)

    {

        printf("start thread failed,errno:%d/n",::GetLastError());

        CloseHandle(hStartEvent);

        return 1;

    }

 

    //wait thread start event to avoid PostThreadMessage return errno:1444

    ::WaitForSingleObject(hStartEvent,INFINITE);

    CloseHandle(hStartEvent);

 

    int count = 0;

    while(true)

    {

        char* pInfo = new char[MAX_INFO_SIZE]; //create dynamic msg

        sprintf(pInfo,"msg_%d",++count);

        if(!PostThreadMessage(nThreadID,MY_MSG,(WPARAM)pInfo,0))//post thread msg

        {

            printf("post message failed,errno:%d/n",::GetLastError());

            delete[] pInfo;

        }

        ::Sleep(1000);

    }

 

    CloseHandle(hThread);

    return 0;

}

 

要把SETTING 改爲多線程的

Project->Settings->click C/C tab,

Category 中選Code Generation, 然後在Use run-time libray 中選一個

Multithread 配置

發佈了31 篇原創文章 · 獲贊 5 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章