Problem Description
One barber barber shop, a barber chair and N to wait for customers to sit in a chair.
If there are no customers in the barber chair barber sleep;
when there is a customer come when he must wake barber;
if a customer getting a haircut to the barber, if empty chair, sit down and wait, or else leave.
With P, V and sync operations to solve the aforementioned problems in a mutually exclusive relationship.
analysis
Customers will be treated as N producers, is a barber consumers.
Barber chair and resources are critical, it is a mutually exclusive relationship between the customer;
barber and customer relations are synchronized.
Semaphore set
1、 Semaphore barberReady = 0 互斥量,只能取0或1 2、 Semaphore accessSeat = 1 互斥量,如果为1,表明椅子数可以增加或减少, 相当于给椅子加锁,避免两个顾客同时坐一把椅子 3、 Semaphore num_wait = 0 坐在椅子上等待的顾客数 4、 int seat_free = n 空着的椅子数目
/*顾客进程*/
void customer()
{
while(true)
{
P(accessSeat); // 获得对椅子操作的权限
if(seat_free > 0) {
seat_free--; // 获得椅子
V(num_wait); // 试图唤醒理发师,
V(accessSeat); // 不用再锁着椅子
P(baberReady); // 等待理发师ready
理发;
}
else {
V(accessSeat); //释放加在椅子上的锁
离开;
}
}
}
/*理发师进程*/
void barber(){
while(true){
P(num_wait); //尝试获得一位顾客,如果没有,去睡觉
P(accessSeat); //尝试获得椅子锁,更改空闲椅子数目
seat_free++; //空椅子加1
V(baberReady); //理发师准备好了
V(accessSeat); //无需继续锁着椅子
理发;
}
}