The Sleepy Barber Problem

Tom Kelliher, CS 318

Mar. 2, 1998

Problems with the previous approach:

  1. Race condition on the chair semaphore: one process signals, two wait.

  2. No explicit knowledge of whether or not the barber is asleep: another race condition.

Global variables:

Semaphore door(0);      // Mutex to shared variables.
Semaphore chair(0);     // Haircut synch., barber sleep.
Semaphore q(0);         // Waiting customers.

bool sleeping = FALSE;  // Barber sleeping.
int waiting = 0;        // # of waiting customers.

Barber:

door.signal();
while (1)
{
   door.wait();

   if (waiting == 0)
   {
      sleeping = TRUE;
      door.signal();
      chair.wait();
   }
   else
   {
      q.signal();
      --waiting;
      door.signal();

   cut hair;         // Rendezvous.
   chair.wait();     // Synch.
}

Customer:

door.wait();
if (waiting == N)
{
   door.signal();
   leave;
}
else if (sleeping)
{
   sleeping = FALSE;
   chair.signal();
   door.signal();
   get hair cut;     // Rendezvous.
   chair.signal();   // Synch.
}
else
{
   ++waiting;
   door.signal();    // Fairness problem???
   q.wait();
   get hair cut;     // Rendezvous.
   chair.signal();   // Synch.
}



Thomas P. Kelliher
Sun Mar 1 20:10:52 EST 1998
Tom Kelliher