PostThreadMessage 线程的消息

PostThreadMessage

PostThreadMessage

  函数功能:该函数将一个消息放入(寄送)到指定线程的消息队列里,不等待线程处理消息就返回。

  函数原型:BOOL PostThreadMessage(DWORD idThread,UINT Msg,WPARAM wParam,LPARAM IParam);

  参数

  idThread:其消息将被寄送的线程的线程标识符。如果线程没有消息队列,此函数将失败。当线程第一次调用一个Win 32 USER或GDI函数时,系统创建线程的消息队列。要得到更多的信息,参见备注。

  Msg:指定将被寄送的消息的类型。

  wParam:指定附加的消息特定信息。

  IParam:指定附加的消息特定信息。

  返回值:如果函数调用成功,返回非零值。如果函数调用失败,返回值是零。若想获得更多的错误信息,请调用GetLastError函数。如果idThread不是一个有效的线程标识符或由idThread确定的线程没有消息队

  列,GetLastError返回ERROR_INVALID_THREAD。

  备注:消息将寄送到的线程必须创建消息队列,否则调用PostThreadMessage会失败。用下列方法之一来处理这种情况:

  调用PostThreadMessage。如果失败,调用Sleep,再调用PostThreadMessage,反复执行,直到PostThreadMessage成功。

  创建一个事件对象,再创建线程。在调用PostThreadMessage之前,用函数WaitForSingleObject来等特事件被设置为被告知状态。消息将寄送到的线程调用PeekMessage(£msg,NULL,WM_USER,WM_USER,PM_NOREMOVE)来强制系统创建消息队列。设置事件,表示线程已准备好接收寄送的消息。

  消息将寄送到的线程通过调用GetMesssge或PeekMesssge来取得消息。返回的MSG结构中的hwnd成员为NULL。

  速查:Windows NT:3.1及以上版本;Windows:95及以上版本;Windows CE:1.0及以上版本:头文件:winuser.h;输入库:user32.lib;Unicode:在Windows NT环境下以Unicode和ANSI方式实现。

---------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------

把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 eventif(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 msgsprintf(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 配置
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值