理发师





#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;
}







  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值