c++线程间通过PostThreadMessage和GetMessage函数进行通信,下面用代码演示两个线程间的通信:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include <stdio.h>
#include<windows.h>
using namespace std;
DWORD WINAPI ThreadFun1(LPVOID param);
DWORD WINAPI ThreadFun2(LPVOID param);
#define MY_MSG WM_USER+1 //定义用户消息
int main()
{
DWORD threadID1;
HANDLE hThread1 = CreateThread(NULL,0, ThreadFun1,NULL,0, &threadID1);
HANDLE hThread2= CreateThread(NULL,0, ThreadFun2,(PVOID)threadID1,0, NULL);
HANDLE hThread[] = { hThread1 ,hThread2 };
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
return 0;
}
DWORD WINAPI ThreadFun1(LPVOID param)
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
switch (msg.message)
{
case MY_MSG:
printf("收到消息%d\n", msg.wParam);
break;
}
}
printf("收到WM_QUIT\n");
return 0;
}
DWORD WINAPI ThreadFun2(LPVOID param)
{
DWORD threadId = (DWORD)param;
int N = 1;
while (true)
{
if (N <= 10) {
PostThreadMessage(threadId, MY_MSG, (WPARAM)N++, NULL);
}
else {
PostThreadMessage(threadId, WM_QUIT, NULL, NULL);
break;
}
Sleep(1000);
}
return 0;
}