【操作系统】【信号量】理发师问题

The Sleeping-Barber Problem. A barbershopconsists of a waiting room with n chairs and the barber room containing thebarber chair. If there are no customers to be served, the barber goes to sleep.If a customer enters the barbershop and all chairs are occupied, then thecustomer leaves the shop. If the barber is busy but chairs are available, thenthe customer sits in one of the free chairs. If the barber is asleep, thecustomer wakes up the barber. Write a program to coordinate the barber and the customers.


Int wait =0;

Int chairs=n;

Int babers=0;

Semaphore customs=0, babers=0, mutex=1;

 

Baber(){
         while(true);

         P(customers);//服务一个顾客

         P(mutex);//进入临界区

         Waiting:=waiting-1;//等待顾客数-1

         V(babers);//理发师临界区开放

         V(mutex);//开放临界区

         Cut_hair();//理发

}

 

Customer(){

         P(mutex);//进入临界区

         If(waiting<=chairs){

                   Waiting:=waiting-1;//没有超过则等待人数+1

                   V(babers);//唤醒一下理发师

                   V(mutex);//开放临界区

                   P(babers);//使用理发师

                   Get_haircut();//理发

         }

         ElseV(mutex); //如果等待人数超过椅子数,离开

}

你可能感兴趣的:(【操作系统】【信号量】理发师问题)