{
_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传递的消息如果要包含信 息,要注意在结束的时候释放消息中的信息。(2.如果是post动态分配的memory给另外一个thread,要注意内存的正确释放。)
在消息中附加信息方法如下
/*构造信息如下*/
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_USER100
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
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/ruanjian/article-49688-7.html
不懂就别装了
美日口粮做事的啦