barber question

理发师问题:
一个理发店由一个有几张椅子的等待室和一个放有一张理发椅的理发室组成。
1. 若没有要理发的顾客,则理发师去睡觉;
2. 若一顾客进入理发店,理发师正在为别人理发,且等待室有空椅子,则该顾客就找张椅子按顺序坐下;
3. 若一顾客进入理发店,理发师在睡觉,则叫醒理发师为该顾客理发;
4. 若一顾客进入理发店且所有椅子都被占用了,则该顾客就离开。

互斥信号量:mutex 用来互斥对临界变量waiting的访问

计数信号量 customers用来记录等候的顾客数据,二进制信号量barber用来表示理发师是否可用;

临界变量:waiting由理发师进程和顾客进程共同访问,用来记录在椅子上等着的顾客数

              N 为椅子数,为最多等候的顾客数

#define CHAIRS 5 
typedef int semaphore ;

semaphore mutex = 1 ;
semaphore customers = 0 , barber = 0 ;
int waiting = 0 ;

void Customer() {
while (true) {
// Is there any empty seat
wait(mutex) ;
if (waiting < CHAIRS) {
/*
Some empty seats => seat down
*/
waiting ++ ;
// if the barber is sleeping, wakes up him
signal(customers) ;
signal(mutex) ;
/*
Is the barber working
yes => waiting
*/
wait(barber) ;
// no => get hair cutting
// get the hair cut
}
else {
// No empty seats => leave
signal(mutex) ;
}
}
}

void Barber() {
while (true) {
/*
Is there any customer waiting
(check current customers)
No customers => sleep
*/
wait(customers) ;
/*
some customers =>
select a customer
and cut hair for him
*/
wait(mutex) ;
waiting -- ;
signal (barber) ;
signal(mutex) ;
// cut the hair
} // Finish cutting
}

流程图:

老师所给PPT解法:

转载于:https://www.cnblogs.com/diyingyun/archive/2011/12/04/2275240.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值