Skip to content
Related Articles

Related Articles

FIFO Barbershop in Process synchronization

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 27 Aug, 2021
View Discussion
Improve Article
Save Article

Overview :
In process synchronization, there exists a Sleeping Barber problem, as discussed here. But in the above solution, there is no guarantee that the customers are served in the order they arrive in the barbershop, i.e. there is no guarantee that the customers enter a FIFO manner(First-in First-out). In the solution discussed above.

  • Up to n customers can arrive, then signal customer and wait for the barber to be idle or awake.
  • Once the barber is idle or awaken, any of the customers may proceed.

Pre-requisite –
Sleeping Barber problem in Process Synchronization

Problem Statement : 
We want a solution, in which the customers are served in order of their arrival inside the shop.

Solution –
To maintain the order of the customers, we should implement a data structure, known as Queue, which follows the First-in First-out principle. Instead of using a single Semaphore for customers, a list of Semaphore will be used. From now onward, we will refer a customer as a thread. So for threads, a list of Semaphore will be used, named as a queue. The intuition behind this approach is that:

  1. As each thread enters the barbershop, it creates a thread and puts it in the queue. 
  2. Instead of waiting for the barber to be idle, each thread waits on its own semaphore.
  3. Whenever a barber is either idle or awaken, he removes the thread from the queue, and signals it to proceed to the chair.

Note –
The barber has to get the mutex to access the queue. Hence, the mutex will use some Semaphore to control the thread’s access to the queue, and the barber processes the queue.

Algorithm for the FIFO Barbershop Problem :

Semaphore customer = 0;
Semaphore mutex = 1;
Semaphore barberDone = 0;
Semaphore customerDone = 0;
customer = 0;
Queue queue;

/* Number of chairs available */
n = 4

/* Protects the seat, to mark the present customer */
    Semaphore self = 0;
    if(customer == n){
/* Invoke the barber */
    customer += 1;          
/* Adds the thread inside the queue */
/* gets the hair cut */
/* Decrements the number of thread by one */
    mutex . wait ();
    customers -= 1;
    mutex . signal ();

/* To store the current thread*/
    Semaphore curr;
/* Gets the current thread*/
    curr = queue.pop();
    /* gets the hair cut */


Note –
The self and curr are nothing but are semaphores referring to the current thread.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!