理发师问题

一个理发店有一张可以坐N人的沙发和n个理发椅和n个理发师和一个收银员。没有顾客时,理发师睡觉,当一个顾客走进理发店时,如果沙发被坐满,则离开,否则,如果所有理发师正在为其他顾客理发,便在沙发上坐下等待。如果理发师正在睡觉,顾客需将他唤醒。理发完后顾客需付费直到收银员收费才能离开;

用类C语言编写程序

int count = 0; //the number of customers sit on sofa
int chair = n;
bool mutex = 1; // control the count
bool mutex2 = 1; //control the cashier only deal with a customer
int bnum = n; // the number of resting barber
int cnum = 0; // the number of the customer sit in chairs 
int payment = 0;
int receipt = 0;
 
void barber() {
    wait(cnum);
    haircut for the customer;
    signal(bnum);
}

void customer() {
    wait(mutex);
    if(count >= N) { // the sofa is full 
        signal(mutex);
        leave;
    }
    else {
        count++;
        signal(mutex);
        
        wait(chair); // wait for the empty chairs    
        count--;  // leave the sofa
        signal(cnum);
        wait(bnum); //wait for the barber
        haircut;
        signal(chair);
        
        wait(mutex2);  //wait for the cashier
        signal(payment);
        pay;
        wait(receipt);
        leave;
    }
}

void cashier() {
    wait(payment);
    receive payment;
    signal(receipt);
    signal(mutex2);
}

 

转载于:https://www.cnblogs.com/bearcarl/p/8619981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值