事件对象实现线程同步(VS2010)
1、主要用到的函数:
CreateEvent();
ResetEvent(); //将某事件对象设置为非信号状态;
SetEvent(); //将某事件对象设置为有信号状态;
//TRUE代表人工重置的事件对象,当事件有信号时,多有等待的线程都变为可调度线程,可同时运行;最好不要采用人工重置的事件对象;采用自动重置的事件对象,只有一个线
//程可调度
//FALSE代表非信号状态,最后一个NULL代表匿名的事件对象
hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
实例代码:
#include <windows.h> #include <iostream> #include <stdlib.h> using namespace std; DWORD WINAPI MyThreadProc1(LPVOID lpParameter); DWORD WINAPI MyThreadProc2(LPVOID lpParameter); DWORD WINAPI MyThreadProc3(LPVOID lpParameter); int index = 100; HANDLE hEvent; int main() { HANDLE handle1,handle2,handle3; handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,0,NULL); handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,0,NULL); handle3 = CreateThread(NULL,0,MyThreadProc3,NULL,0,NULL); if(NULL == handle1) { cout<<"Create Thread failed !"<<endl; return -1; } if(NULL == handle2) { cout<<"Create Thread failed !"<<endl; return -1; } if(NULL == handle3) { cout<<"Create Thread failed !"<<endl; return -1; } CloseHandle(handle1); CloseHandle(handle2); CloseHandle(handle3); hEvent = CreateEvent(NULL,FALSE,TRUE,NULL); SetEvent(hEvent); Sleep(2000); system("PAUSE"); return 0; } DWORD WINAPI MyThreadProc1(LPVOID lpParameter) { while(true) { WaitForSingleObject(hEvent,INFINITE); if(index > 0) { Sleep(1); cout<<"The Index1 Number is : "<<index--<<endl; } else break; } return 0; } DWORD WINAPI MyThreadProc2(LPVOID lpParameter) { while(true) { WaitForSingleObject(hEvent,INFINITE); if(index > 0) { Sleep(1); cout<<"The Index2 Number is : "<<index--<<endl; } else break; SetEvent(hEvent); } return 0; } DWORD WINAPI MyThreadProc3(LPVOID lpParameter) { while(true) { WaitForSingleObject(hEvent,INFINITE); if(index > 0) { Sleep(1); cout<<"The Index3 Number is : "<<index--<<endl; } else break; } return 0; }