[ Previous: 2.1 Implementation of Semaphores | Up: 2.2 Classical Problems | Next: 2.2.2 Cigarette Smokers ]

2.2.1 Sleeping Barber

Scenario

Consider a barber’s shop where there is only one barber, one barber chair and a number of waiting chairs for the customers. When there are no customers the barber sits on the barber chair and sleeps. When a customer arrives he awakes the barber or waits in one of the vacant chairs if the barber is cutting someone else’s hair. When all the chairs are full, the newly arrived customer simply leaves.

Problems

Use of Semaphores

The solution to these problems involves the use of three semaphores out of which one is a mutex (binary semaphore). They are:

The Procedure

Implementation

The following pseudo-code guarantees synchronization between barber and customer and is deadlock free, but may lead to starvation of a customer.

Customers = init(0)
Barber = init(0)
accessSeats = init(1) // mutex
NumberOfFreeSeats = N //total number of seats

The Barber (Thread/Process)

while (true) { // runs in an infinite loop

    P(Customers) // tries to acquire a customer - if none is available
                    he goes to sleep

    P(accessSeats) // at this time he has been awaken - want to modify
                      the number of available seats

    NumberOfFreeSeats++ // one chair gets free

    V(Barber) // the barber is ready to cut

    V(accessSeats) // we don't need the lock on the chairs anymore
                   // here the barber is cutting hair

}

The Customer (Thread/Process)

P(accessSeats) // tries to get access to the chairs

if (NumberOfFreeSeats > 0) { // if there are any free seats

    NumberOfFreeSeats-- // sitting down on a chair

    V(Customers) // notify the barber, that there is a customer waiting

    V(accessSeats) // don't need to lock the chairs anymore

    P(Barber) // now it's this customers turn, but wait if the barber is busy
              // here the customer is having his hair cut

} else { // there are no free seats

    // tough luck

    V(accessSeats) // but don't forget to release the lock on the seats
                   // customer leaves without a haircut
}

Note: The solution can be modified so that the customers are made to form a queue as they arrive so that the barber can service these customers on a first come first served basis. This solves the problem of starvation where in a customer might have to wait long for his turn to come.

Animation

Please click START to begin.

References
1. Sleeping Barber Problem (Wikipedia)

[ Previous: 2.1 Implementation of Semaphores | Up: 2.2 Classical Problems | Next: 2.2.2 Cigarette Smokers ]