多线程 调用自动事件对象失败
#include<iostream>#include<windows.h>
using std::cout;
DWORD WINAPI fun1(LPVOID lpParameter);
DWORD WINAPI fun2(LPVOID lpParameter);
int ticket=100;
//HANDLE hMutex;
HANDLE g_hEvent;
int main()
{
HANDLE hTreadl,hTread2;
g_hEvent=CreateEvent(NULL,FALSE,FALSE,"tickets");
if(g_hEvent)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run\n";
return 0;
}
}
hTreadl=CreateThread(NULL,0,fun1,NULL,0,NULL);
hTread2=CreateThread(NULL,0,fun2,NULL,0,NULL);
CloseHandle(hTreadl);
CloseHandle(hTread2);
Sleep(4000);
CloseHandle(g_hEvent);
return 0;
}
DWORD WINAPI fun1(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(g_hEvent,INFINITE);
if(ticket>0)
{
cout<<"thread1 sell ticket:"<<ticket--<<std::endl;
SetEvent(g_hEvent);
}
else
{
SetEvent(g_hEvent);
break;
}
//ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI fun2(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(g_hEvent,INFINITE);
if(ticket>0)
{
cout<<"thread2 sell ticket:"<<ticket--<<std::endl;
SetEvent(g_hEvent);
}
else
{
SetEvent(g_hEvent);
break;
}
//ReleaseMutex(hMutex);
}
return 0;
}
//
//
//大神能看看我的代码 为什么执行到WaitForSingleObject(g_hEvent,INFINITE);不往下执行了???