操作系统——理发师问题

问题描述:

理发店理有一位理发师、一把理发椅和n把供等候理发的顾客坐的椅子 如果没有顾客,理发师便在理发椅上睡觉 一个顾客到来时,它必须叫醒理发师 如果理发师正在理发时又有顾客来到,则如果有空椅子可坐,就坐下来等待,否则就离开

程序模型:

int waiting=0;//等候理发顾客数
int CHAIRS=N; //为顾客准备的椅子数
semaphore customers,barbers,mutex;//信号量 
customers=0;// 顾客 
barbers=0;//理发椅上人数 
mutex=1;//互斥信号量 

//理发师 
process barber( ) {
 while(true) {
 P(customers); //有顾客吗?若无顾客,理发师睡眠
 
 P(mutex);          //若有顾客时,进入临界区
    waiting--;      //等候顾客数少一个
    V(barbers);        //理发师准备为顾客理发
 V(mutex);          //退出临界区
   
    cut_hair();     //理发师正在理发(非临界区)
    }
}

//顾客 
process customer_i( ) {
  P(mutex);             //进入临界区
 
  if(waiting<CHAIRS) {  //有空椅子吗
        waiting++;       //等候顾客数加1
        V(customers);      //唤醒理发师
  V(mutex);          //退出临界区
    
    P(barbers);     //理发师忙,顾客坐下等待
    get_haircut();   //否则顾客坐下理发
      }
  else
  
   V(mutex);          //人满了,走吧!
}

猜你喜欢

转载自www.cnblogs.com/junfblog/p/12811550.html
今日推荐