#include<iostream>
#include<Windows.h>
using namespace std;
DWORD WINAPI ThreadProc1(LPVOID lpParameter);
DWORD WINAPI ThreadProc2(LPVOID lpParameter);
HANDLE hEvent;
int tickets = 100;
int main()
{
hEvent = CreateEvent(NULL,FALSE,TRUE,NULL);
HANDLE hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
HANDLE hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
DWORD nCount = 2;
HANDLE* lpHandles = new HANDLE[nCount];
lpHandles[0] = hThread1;
lpHandles[1] = hThread2;
WaitForMultipleObjects(nCount,lpHandles,TRUE,INFINITE);
CloseHandle(hThread2);
CloseHandle(hThread1);
CloseHandle(hEvent);
return 0;
}
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hEvent,INFINITE);
if(tickets > 0)
{
cout<<"ThreadProc1 sells "<<tickets--<<endl;
SetEvent(hEvent);
}
else
{
SetEvent(hEvent);
break;
}
}
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hEvent,INFINITE);
if(tickets > 0)
{
cout<<"ThreadProc2 sells "<<tickets--<<endl;
SetEvent(hEvent);
}
else
{
SetEvent(hEvent);
break;
}
}
return 0;
}