C++ 多线程阻塞 (多线程同步)(MsgWaitForMultipleObjects)

时间:2021-04-09 13:02:37

在主线程定要禁止使用waitforsingleobject(),原因是会阻塞主线程的消息循环,所以必须使用另一种 MsgWaitForMultipleObjects,即可以让消息通过,下面就是一个基于MsgWaitForMultipleObjects与Event,实现多线程同步这样。

HANDLE g_Handle;//全局的句柄

g_Handle=CreateEvent(NULL,FALSE,FALSE,NULL);
ResetEvent(g_Handle); //无信号,即阻塞了
//block here till the event was signal
while(TRUE)
{
DWORD result;
MSG msg;
result=MsgWaitForMultipleObjects(1,&g_Handle,FALSE,INFINITE,QS_ALLINPUT);
if(WAIT_OBJECT_0 == result)
break;
PeekMessage(&msg,NULL,0,0, PM_REMOVE);
DispatchMessage(&msg);
}
//在另一个线程调用setEvent(g_Handle);即变为有信号状态,阻塞即解除
//do something~

更多文章:http://blog.csdn.net/what951006?viewmode=list
powered by:小乌龟在大乌龟背上~