/    /  OS – Sleeping Barber Problem

Sleeping Barber Problem

 

This problem is based on a hypothetical barbershop with one barber. 

When there are no customers, the barber sleeps in his chair. If any customer enters he will wake up the barber and sit in the customer chair. If there are no chairs empty they wait in the waiting queue.

 

The problem is to program the customer and the barber without getting in race condition.

 

The solution of this problem is to include three Semaphores. 

The first one to count the number of customers present in the waiting room. 

The second one for the barber. 0 and 1 are used to signify if the barber is idle or not.

The third mutex is for mutual exclusion. It is needed for the program to run.

The customer keeps a track of the number of customers in the waiting line.

If the number of customers in the waiting line is equal to the number of waiting chairs, then the upcoming customer leaves the barbershop.

 

The barber executes the barber procedure, blocking the semaphore customers because it is initially 0. 

Then the barber sleeps until the first customer shows up.

When the customer arrives, the customer procedure is executed, the customer acquires mutex to enter the critical zone. 

 

The customer checks if there are any waiting chairs, if there are empty waiting chairs then the customer stays, and if not, it leaves.

If the customer stays, there is an increment in the variable waiting value, which increases the customer’s semaphore, and that wakes up the customer. 

 

When the barber is awake and the customer is also present, he gives the customer a haircut. When the procedure is complete, the customer exits. 

Another customer would enter if there are any in the waiting queue, if not the barber will go to sleep.

 

Reference

Sleeping Barber Problem