多线程 事件对象的问题
#include <iostream>#include <Windows.h>using namespace std;DWORD WINAPI Fun1Proc(LPVOID lpParameter);DWORD WINAPI Fun2Proc(LPVOID lpParameter);int tickets=100;HANDLE g_hEvent;int main(){ HANDLE hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); HANDLE hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); //it does not close the thread CloseHandle(hThread1); CloseHandle(hThread2); //initialize the event object to be non signaled state //do not use manual reset mode g_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL); //set the event object to be signaled state SetEvent(g_hEvent); Sleep(4000); return 0;}DWORD WINAPI Fun1Proc(LPVOID lpParameter){ while(TRUE){ WaitForSingleObject(g_hEvent,INFINITE);// ResetEvent(g_hEvent); if (tickets>0) { cout<<"thread1 sells ticket:"<<tickets--<<endl; } else{ break; } SetEvent(g_hEvent); } return 0;}DWORD WINAPI Fun2Proc(LPVOID lpParameter){ while(TRUE){ WaitForSingleObject(g_hEvent,INFINITE);// ResetEvent(g_hEvent); if (tickets>0) { cout<<"thread2 sells ticket:"<<tickets--<<endl; } else{ break; } SetEvent(g_hEvent); } return 0;}
thread1 sells ticket:15
thread2 sells ticket:14
thread1 sells ticket:13
thread2 sells ticket:12
thread1 sells ticket:11
thread2 sells ticket:10
thread1 sells ticket:9
thread2 sells ticket:8
thread1 sells ticket:7
thread2 sells ticket:6
thread1 sells ticket:5
thread2 sells ticket:4
thread1 sells ticket:3
thread2 sells ticket:2
thread1 sells ticket:1
已经用了事件对象来阻塞了,为什么第一行的输出会是这个样子呢?.
[解决办法]
g_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
把这句放到创建线程前面。不然线程先跑起来事件还没创建好,一个无效的事件句柄,waitforsingleobkect会马上返回的,跟木有同步一样