原文地址:postthreadmessage
作者:lause
PostThreadMessage
把window线程间传送消息仔细的看了一遍,觉得以前的理解很不深刻。说一说对PostThreadMessage的理解。
PostThreadMessage是一个线程体发送一个消息到指定的线程ID,其原型如下:
BOOLPostThreadMessage(
DWORD idThread,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
1.
2.
假设mainAPP是发送线程ThreadA是接受线程
……
hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event
if(hStartEvent == 0)
{
printf("create start event failed,errno:%dn",::GetLastError());
return 1;
}
::WaitForSingleObject(hStartEvent,INFINITE);
CloseHandle(hStartEvent);
if(!PostThreadMessage(threadaID, WM_MESSAGE_A,0,0))
{
_tprintf(_T("post error! %dn"), GetLastError());
return 1;
}
……
ThreadA是接受线程
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
if(!SetEvent(hStartEvent))
{
printf("set event error,%dn",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)//postthread 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 %sn",pInfo);
delete[] pInfo; //这里释放了资源
break;
}
}
做了一个简单的消息通信实验,让主线程中等待用户输入,产生不同的消息,并把这些消息post给子线程,子线程根据产生的消息做出不同的反映。这些子线程可以是工作线程也可以是UI线程。
#include #include #include #define const HANDLE // unsigned { } int { } |
要把SETTING 改为多线程的
Project->Settings->click C/C tab,
在Category 中选Code Generation, 然后在Use run-time libray 中选一个
Multithread 配置
Project->Settings->click C/C tab,
在Category 中选Code Generation, 然后在Use run-time libray 中选一个
Multithread 配置