理发师问题Customer&Barber
· 理发师由等待间(包含N个等待座位)和理发间(一把理发椅)构成。
· 没有顾客时,理发师睡觉;顾客进入理发店发现理发师睡觉则唤醒他,如果座位已满就离开。
下面是该问题的伪代码表述:
const chairs=5;
//一般信号量customers表示顾客的人数
//互斥信号量barber,mutex--控制对变量waiting的互斥访问
Semaphore customers=0,barber=1,mutex=1;
int waiting=0;
begin
parbegin
//barber:
begin
repeat
wait(custmers);//有无顾客理发
wait(mutex);
waiting--;
signal(mutex);//释放冲突变量
cutting;
signal(barber)//释放理发师
until false;
end
//customers:
begin
repeat
wait(mutex);
if(waiting<chairs)
then begin
waiting++;//等待顾客+1
signal(customers);//有顾客要理发
signal(mutex);
wait(barber);//申请理发师
getting haircut;
end
else signal(mutex);//满员则离店
until false;
end
parend
end
理发师问题是操作系统经典同步问题中——生产者-消费者问题的典例,通常使用互斥信号量mutex用于控制对缓冲区的互斥访问,初始化为1。该问题又称为有限缓冲问题。