操作系统(三)同步进程问题--理发师的睡觉问题

来源:互联网 发布:java 线程是什么 编辑:程序博客网 时间:2024/04/30 19:09

The Sleeping-Barber Problem.

A barbershop consists of a waiting room with n chairs and barber room containing the barber chair.If these are no customers to be served ,the barber goes to sleep.If a customer enters the barbershop and all chairs are occupied,then the customer leaves the shop. If the barber is busy but chairs are available,then customer sits in one of the free chairs.If the barber is asleep,the customer wakes up the barber.Write a program to coordinate the barber and the customers.

一个理发店由一个含有n把椅子等候房间和一个只有一把理发椅子的剪发房间组成。如果没有顾客的时候,发型师就去睡觉了。如果一位顾客到来时,理发店的所有椅子都没有空闲,那么这位顾客会离开。如果理发师正在给顾客剪头发,理发店还有空闲的椅子,那么在此时到达的顾客会坐下等待。如果理发师睡着了,顾客会唤醒理发师。写一个程序去处理理发师和顾客的关系。


对于问题,首先需要思考进程个数、信号量个数、共享资源和互斥信号的问题。

在此问题中:
进程个数:2,理发师与顾客
信号量个数:5,空闲椅子情况empty,full;理发师状态cut;椅子总数N;互斥信号量mutex
共享资源:count
同时,剪发师可以看作生产者与消费者的问题,顾客可以看作读者写者问题。

我个人的一些思考,不一定正确,需慎重!
对于顾客:三种情况

  1. 第一个顾客到达,那么直接剪发,count=1,空闲椅子依然为N,此时是full还是empty修改呢?!
  2. 当第二个或第N+1个顾客到达,count=[2,N+1],空闲椅子数为[N-1,0]。
  3. 当第N+2个顾客到达,那么直接离开。

对于剪发师:两种情况

  1. 有顾客到来的时候,也就是count不等于0,那么剪发。
  2. 当count=0时,那么剪发师就可以睡觉了。

最后,应该怎么考虑顾客剪完头发的椅子释放问题呢?!

Semaphore mutex=1,chair=N,empty=1,full=0,cut=0;          int  count=0;
Barber:     while(1)    {        wait(full);        cut hair;        signal(cut);    }
Guest:    while(1)    {        wait(mutex);             //互斥信号减一,以下的执行都必须满足这一条,否则阻塞在此        if (count>N)             //顾客人数大于椅子个数        {            signal(mutex);       //释放互斥信号            exit  shop;          //离开店铺        }       else        {           count++;              //椅子还有空闲的时候           if (count>1)            {               wait(chair);     //顾客加一,椅子就要释放一               sit on chair;               wait(empty);     //此为等待剪发师空闲               get up from chair;               signal(chair);   //椅子唤醒           }            else                wait(empty);          signal(mutex);         sit on the baber_chair;         signal(full);         //这是无条件的加一,此时理发师可以开始工作了         wait(cut);            //有条件的减一,当这两条都满足的时候,就可以剪发了         cutting;         get up from the baber_chair;               signal(empty);      //释放理发的座位         wait(mutex);        //加互斥信号,不允许同时对count进行修改         count- -;         signal(mutex);         exit shop;      }    }