Despierta el sistema operativo del problema del peluquero durmiente

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <windows.h>
#include <io.h>
#include <conio.h>
#include  <stdlib.h>
#include <fstream>
using namespace std;
#define MAXCHAIR 3
#define MAX_THREAD_NUM 10
int chairs,thread_id;
HANDLE h_Mutex, h_Barber, h_Customer;//信号量
//使用WINAPI创线程
DWORD WINAPI CustomerThread(void *p);
DWORD WINAPI BaberThread(void *p);
DWORD WINAPI BaberThread(void *p)
{
    while(1)
    {
        WaitForSingleObject(h_Customer,-1);//P信号量
        WaitForSingleObject(h_Mutex,-1);//P信号量
        chairs++;//空位+1
        ReleaseSemaphore(h_Barber,1,NULL);//V信号量
        ResumeThread((HANDLE)CustomerThread);//唤醒等待顾客
        ReleaseMutex(h_Mutex);//V信号量
        cout <<"*************理发师开始理发!"<<endl;
        Sleep(4000);
        cout <<"*************理发师结束理发!"<<endl;
    }
    return 0;
}
DWORD WINAPI CustomerThread(void *p)
{
    int id = ++thread_id;//顾客标号
    cout<<"顾客 "<<id<<" 发送理发请求."<<endl;
    WaitForSingleObject(h_Mutex,-1);//P信号量
    if(chairs > 0)//有等待位置
    {
        chairs--;
        cout<<"顾客 "<<id<<" 坐下并等待理发,"<<"总共等待人数"<<MAXCHAIR-chairs<<endl;
        ReleaseSemaphore(h_Customer,1,NULL);
        ResumeThread((HANDLE)BaberThread);
        ReleaseMutex(h_Mutex);

        cout<<"顾客 "<<id<<" 准备理发."<<endl;
        WaitForSingleObject(h_Barber,-1);
        cout<<"顾客 "<<id<<" 正在理发."<<endl;
        Sleep(3000);
        cout<<"顾客 "<<id<<" 理发结束并离开."<<endl;
    }
    else
    {
        cout<<"顾客 "<<id<<" 无座,离开."<<endl;
        ReleaseMutex(h_Mutex);
    }
    return 0;
}
void pro()
{
    //初始化
    h_Mutex = CreateMutex(NULL, FALSE, "mutex");
    h_Barber = CreateSemaphore(NULL, 0, 1, "barber");
    h_Customer = CreateSemaphore(NULL, 0, MAXCHAIR, "customer");

    HANDLE h_Thread;
    chairs=MAXCHAIR;
    cout<<"程序开始:"<<endl;
    cout<<endl;
    thread_id = 0;
    //创建理发师线程
    h_Thread=CreateThread(NULL,0,BaberThread,NULL,0,NULL);
    //创建顾客线程
    for(int i=0; i<MAX_THREAD_NUM; i++)
    {
        h_Thread=CreateThread(NULL,0,CustomerThread,NULL,0,NULL);
        Sleep(3000);
    }

    CloseHandle(h_Mutex);
    CloseHandle(h_Barber);
    CloseHandle(h_Customer);
    CloseHandle(h_Thread);
}
int main()
{
    int num;
    int cnt = 0;
    cout<<"************************************"<<endl;
    cout<<endl;
    cout<<"|             1.程序开始            |"<<endl;
    cout<<"|             2.退出程序            |"<<endl;
    cout<<endl;
    cout<<"************************************"<<endl;
start:
    cout<<"请输入你所要进行的选择:"<<endl;
    cin>>num;
    if(num<1||num>2)
    {
        cout<<"输入无效,请重新输入"<<endl;
        goto start;
    }
    else if(num==1)
    {
        cout<<"········顾客数和座位数分别为"<<MAX_THREAD_NUM<<" "<<MAXCHAIR<<"········"<<endl;
        pro();
    }
    else if(num==2)
    {
        exit(0);
    }
    return 0;
}

 

Supongo que te gusta

Origin blog.csdn.net/Puppet__/article/details/85125052
Recomendado
Clasificación