CreateEvent(LPSECURITY_ATTRIBUTESlpEventAttributes,//安全属性
BOOLbManualReset,// 复位方式
BOOLbInitialState,// 初始状态
LPCTSTRlpName // 对象名称
)
lpEventAttributes=NULL此句柄不能被继承
bManualReset=TRUE手动复原
false当一个等待线程被释放后,系统自动将事件状态复原为无信号事件
bInitialState=初始状态
lpName=一个以0结束的字符串指针
SetEvent函数置为有信号
ResetEvent函数置为无信号状态
WaitForSingleObject(HANDLE hHandle,DWORDdwMilliseconds);
hHandle:对象句柄。可以指定一系列的对象,如Event,Mutex,Process,Semaphore,Thread。
dwMilliseconds:定时时间间隔,单位为毫秒,如果指定一个非零值,函数处于等待状态知道hHandle标记的对象触发或者时间到了,如果dwMilliseconds为0,对象没有被触发,函数不会进入一个等待状态,立即返回。如果dwMilliseconds为INFINITE,对象被触发信号后函数才会返回。
实例:
#include"iostream"
#include"windows.h"
#include<cstdio>
usingnamespace std;
DWORDWINAPI ThreadProc1(LPVOID lpParam);
DWORDWINAPI ThreadProc2(LPVOID lpParam);
HANDLEhEvent = NULL;
HANDLEhThread1 = NULL;
HANDLEhThread2 = NULL;
intmain(int argc, char *args[])
{
hEvent = CreateEvent(NULL, TRUE, false, NULL);//使用手动重置为无信号状态,初始化时有信号状态
hThread1 = CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ThreadProc1, NULL, 0, NULL);
Sleep(200);
hThread2 = CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ThreadProc2, NULL, 0, NULL);
Sleep(200);
if (NULL == hThread1 || NULL == hThread2)
{
cout << "create threadfail!";
}
//DWORD dCount = ResumeThread(hThread);
SetEvent(hEvent);
while (1)
{
}
return 0;
}
DWORDWINAPI ThreadProc1(LPVOID lpParam)
{
cout << "in thread1@!"<< endl;
DWORD dReturn = WaitForSingleObject(hEvent,INFINITE);
if (WAIT_OBJECT_0 == dReturn)
{
cout << " thread1signaled ! " << endl;
}
cout << "in thread1--signal" << endl;
//SetEvent(hEvent);
return 0;
}
DWORDWINAPI ThreadProc2(LPVOID lpParam)
{
cout << "in thread2@!"<< endl;
DWORD dReturn =WaitForSingleObject(hEvent, INFINITE);
if (WAIT_OBJECT_0 == dReturn)
{
cout << "thread2signaled ! " << endl;
}
cout << "inthread2--signal" << endl;
return 0;
}