#include <Windows.h>
#include <iostream>
using namespace std;
const int c_WaitChairCount = 5;
HANDLE hSemWaitChair = NULL;
HANDLE hMutexBarChair = NULL;
HANDLE hSemReady = NULL;
HANDLE hSemDone = NULL;
HANDLE hMutexCount = NULL;
int count = 0;
DWORD WINAPI barber()
{
while (true)
{
cout << "理发师等待顾客来理发" << endl;
WaitForSingleObject(hSemReady, INFINITE);
cout << "理发师开始理发...." << endl;
Sleep(2000);
ReleaseSemaphore(hSemDone, 1, NULL);
cout << "理发完成" << endl;
}
}
DWORD WINAPI consumer(LPVOID para)
{
int c = (int)para;
cout << "\n\t\t顾客 " << c << " 来了->" << endl;
WaitForSingleObject(hMutexCount, INFINITE);
if (count < c_WaitChairCount)
{
count += 1;
cout << "\t\t有空椅子,顾客 " << c << " 坐上空椅子,等待理发" << endl;
ReleaseMutex(hMutexCount);
}
else
{
cout << "\t\t没有空椅子,顾客 " << c << "离开了...." << endl;
ReleaseMutex(hMutexCount);
}
WaitForSingleObject(hSemWaitChair, INFINITE);
WaitForSingleObject(hMutexBarChair, INFINITE);
cout << "\t\t顾客 " << c << " 坐上理发椅,开始理发吧" << endl;
ReleaseSemaphore(hSemWaitChair, 1, NULL);
ReleaseSemaphore(hSemReady, 1, NULL);
WaitForSingleObject(hSemDone, INFINITE);
ReleaseMutex(hMutexBarChair);
WaitForSingleObject(hMutexCount, INFINITE);
count -= 1;
cout << "\t\t顾客 " << c << " 理发完成, 帅呆的离开了。。。" << endl;
ReleaseMutex(hMutexCount);
return 0;
}
int main(int argc, char *argv[])
{
hSemWaitChair = CreateSemaphore(NULL, c_WaitChairCount, c_WaitChairCount, NULL);
hMutexBarChair = CreateMutex(NULL, false, NULL);
hSemReady = CreateSemaphore(NULL, 0, 1, NULL);
hSemDone = CreateSemaphore(NULL, 0, 1, NULL);
hMutexCount = CreateMutex(NULL, false, NULL);
HANDLE hBarber = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)barber, NULL, 0, NULL);
CloseHandle(hBarber);
int i = 0;
while (true)
{
HANDLE hCustomer = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)consumer, (LPVOID)(i++), 0, NULL);
CloseHandle(hCustomer);
// 每1秒 来一个顾客
Sleep(1000);
}
getchar();
return 0;
}