It is a synchronization and inter-process communication problem. This problem is based on a barbershop.
A barbershop has a single barber, single barber chair and n number of chairs for customers. When there is no customer in the barbershop then the barber sleeps. When a customer comes, he has to get up the barber. When there are multiple customers, and the barber is cutting one customer’s hair, then the entire customers either wait for their number or they leave the barbershop when all chairs are full.
When the chair is present, the customer waits in the waiting room. It increments the waiting value of the variable. The point at that, both the customer and barber are waking up, and the barber is set to give a haircut. If the haircut is completed, when no any customer in the waiting room, the barber sleeps. The trouble is to program barbers and customers without entering into the race condition.
Sleeping Barber Problem Solution
Here, we use 3 semaphores. Waiting customers are calculated by semaphore customers. The number of free barbers (0,1) is the semaphore barbers. The mutex is used for mutual exclusion.
The semaphore would facilitate two functions: wait() and signal(). One semaphore is also needed to represent the state of the system. Waiting customers are also calculated by a shared data variable customers1, which is a copy of customers. It is needed since there is no path to read the present value of the semaphore.
We can’t access the value of semaphores immediately, so we require it here. We also require a semaphore cutting which assures that the barber won’t cut other customer’s hair before the first customer quits.