15.4.1火车站售票系统模拟程序(Mutex)
#include <iostream>
#include <Windows.h>
using namespace std;
int tickets = 100;
HANDLE hMutex;
DWORD WINAPI ThreadProc1(LPVOID lpParameter);
DWORD WINAPI ThreadProc2(LPVOID lpParameter);
int main()
{
hMutex = CreateMutex(NULL,FALSE,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[2];
lpHandles[0] = hThread1;
lpHandles[1] = hThread2;
WaitForMultipleObjects(nCount,lpHandles,TRUE,INFINITE);
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if (tickets > 0)
{
cout<<"Thread1 sells "<<tickets--<<endl;
ReleaseMutex(hMutex);
}
else
{
ReleaseMutex(hMutex);
break;
}
}
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if (tickets > 0)
{
cout<<"Thread2 sells "<<tickets--<<endl;
ReleaseMutex(hMutex);
}
else
{
ReleaseMutex(hMutex);
break;
}
}
return 0;
}