Open In App

Sleeping Barber problem in Process Synchronization

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The Sleeping Barber problem is a classic problem in process synchronization that is used to illustrate synchronization issues that can arise in a concurrent system. The problem is as follows:

There is a barber shop with one barber and a number of chairs for waiting customers. Customers arrive at random times and if there is an available chair, they take a seat and wait for the barber to become available. If there are no chairs available, the customer leaves. When the barber finishes with a customer, he checks if there are any waiting customers. If there are, he begins cutting the hair of the next customer in the queue. If there are no customers waiting, he goes to sleep.

The problem is to write a program that coordinates the actions of the customers and the barber in a way that avoids synchronization problems, such as deadlock or starvation.

One solution to the Sleeping Barber problem is to use semaphores to coordinate access to the waiting chairs and the barber chair. The solution involves the following steps:

Initialize two semaphores: one for the number of waiting chairs and one for the barber chair. The waiting chairs semaphore is initialized to the number of chairs, and the barber chair semaphore is initialized to zero.

Customers should acquire the waiting chairs semaphore before taking a seat in the waiting room. If there are no available chairs, they should leave.

When the barber finishes cutting a customer’s hair, he releases the barber chair semaphore and checks if there are any waiting customers. If there are, he acquires the barber chair semaphore and begins cutting the hair of the next customer in the queue.

The barber should wait on the barber chair semaphore if there are no customers waiting.

The solution ensures that the barber never cuts the hair of more than one customer at a time, and that customers wait if the barber is busy. It also ensures that the barber goes to sleep if there are no customers waiting.

However, there are variations of the problem that can require more complex synchronization mechanisms to avoid synchronization issues. For example, if multiple barbers are employed, a more complex mechanism may be needed to ensure that they do not interfere with each other.

Prerequisite – Inter Process Communication Problem : The analogy is based upon a hypothetical barber shop with one barber. There is a barber shop which has one barber, one barber chair, and n chairs for waiting for customers if there are any to sit on the chair.

  • If there is no customer, then the barber sleeps in his own chair.
  • When a customer arrives, he has to wake up the barber.
  • If there are many customers and the barber is cutting a customer’s hair, then the remaining customers either wait if there are empty chairs in the waiting room or they leave if no chairs are empty.

Solution : The solution to this problem includes three semaphores.First is for the customer which counts the number of customers present in the waiting room (customer in the barber chair is not included because he is not waiting). Second, the barber 0 or 1 is used to tell whether the barber is idle or is working, And the third mutex is used to provide the mutual exclusion which is required for the process to execute. In the solution, the customer has the record of the number of customers waiting in the waiting room if the number of customers is equal to the number of chairs in the waiting room then the upcoming customer leaves the barbershop. When the barber shows up in the morning, he executes the procedure barber, causing him to block on the semaphore customers because it is initially 0. Then the barber goes to sleep until the first customer comes up. When a customer arrives, he executes customer procedure the customer acquires the mutex for entering the critical region, if another customer enters thereafter, the second one will not be able to anything until the first one has released the mutex. The customer then checks the chairs in the waiting room if waiting customers are less then the number of chairs then he sits otherwise he leaves and releases the mutex. If the chair is available then customer sits in the waiting room and increments the variable waiting value and also increases the customer’s semaphore this wakes up the barber if he is sleeping. At this point, customer and barber are both awake and the barber is ready to give that person a haircut. When the haircut is over, the customer exits the procedure and if there are no customers in waiting room barber sleeps. Algorithm for Sleeping Barber problem:

C




Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex Seats = 1;
int FreeSeats = N;
 
Barber {
      while(true) {
            /* waits for a customer (sleeps). */
            down(Customers);
 
            /* mutex to protect the number of available seats.*/
            down(Seats);
 
            /* a chair gets free.*/
            FreeSeats++;
            
            /* bring customer for haircut.*/
            up(Barber);
            
            /* release the mutex on the chair.*/
            up(Seats);
            /* barber is cutting hair.*/
      }
}
 
Customer {
      while(true) {
            /* protects seats so only 1 customer tries to sit
               in a chair if that's the case.*/
            down(Seats); //This line should not be here.
            if(FreeSeats > 0) {
                  
                  /* sitting down.*/
                  FreeSeats--;
                  
                  /* notify the barber. */
                  up(Customers);
                  
                  /* release the lock */
                  up(Seats);
                  
                  /* wait in the waiting room if barber is busy. */
                  down(Barber);
                  // customer is having hair cut
            } else {
                  /* release the lock */
                  up(Seats);
                  // customer leaves
            }
      }
}


The Sleeping Barber Problem is a classical synchronization problem in which a barber shop with one barber, a waiting room, and a number of customers is simulated. The problem involves coordinating the access to the waiting room and the barber chair so that only one customer is in the chair at a time and the barber is always working on a customer if there is one in the chair, otherwise the barber is sleeping until a customer arrives.

Here’s a Python implementation of the Sleeping Barber Problem using semaphores:

Python3




import threading
import time
import random
 
# Define the maximum number of customers and the number of chairs in the waiting room
MAX_CUSTOMERS = 5
NUM_CHAIRS = 3
 
# Define the semaphores for the barber, the customers, and the mutex
barber_semaphore = threading.Semaphore(0)
customer_semaphore = threading.Semaphore(0)
mutex = threading.Semaphore(1)
 
# Define a list to keep track of the waiting customers
waiting_customers = []
 
# Define the barber thread function
def barber():
    while True:
        print("The barber is sleeping...")
        barber_semaphore.acquire()
        mutex.acquire()
        if len(waiting_customers) > 0:
            customer = waiting_customers.pop(0)
            print(f"The barber is cutting hair for customer {customer}")
            mutex.release()
            time.sleep(random.randint(1, 5))
            print(f"The barber has finished cutting hair for customer {customer}")
            customer_semaphore.release()
        else:
            mutex.release()
     
# Define the customer thread function
def customer(index):
    global waiting_customers
    time.sleep(random.randint(1, 5))
    mutex.acquire()
    if len(waiting_customers) < NUM_CHAIRS:
        waiting_customers.append(index)
        print(f"Customer {index} is waiting in the waiting room")
        mutex.release()
        barber_semaphore.release()
        customer_semaphore.acquire()
        print(f"Customer {index} has finished getting a haircut")
    else:
        print(f"Customer {index} is leaving because the waiting room is full")
        mutex.release()
 
# Create a thread for the barber
barber_thread = threading.Thread(target=barber)
 
# Create a thread for each customer
customer_threads = []
for i in range(MAX_CUSTOMERS):
    customer_threads.append(threading.Thread(target=customer, args=(i,)))
     
# Start the barber and customer threads
barber_thread.start()
for thread in customer_threads:
    thread.start()
     
# Wait for the customer


Output:

The barber is sleeping…
Customer 0 is waiting in the waiting room
The barber is cutting hair for customer 0
Customer 1 is waiting in the waiting room
Customer 2 is waiting in the waiting room
The barber has finished cutting hair for customer 0
Customer 0 has finished getting a haircut
The barber is cutting hair for customer 1
Customer 3 is waiting in the waiting room
The barber has finished cutting hair for customer 1
Customer 1 has finished getting a haircut
The barber is cutting hair for customer 2
Customer 4 is waiting in the waiting room
The barber has finished cutting hair for customer 2
Customer 2 has finished getting a haircut
The barber is cutting hair for customer 3
Customer 3 has finished getting a haircut
The barber is cutting hair for customer 4
Customer 4 has finished getting a haircut
The barber is sleeping…

The Sleeping Barber Problem is a classical synchronization problem that involves coordinating the access to a barber chair and a waiting room in a barber shop. The problem requires the use of semaphores or other synchronization mechanisms to ensure that only one customer is in the barber chair at a time and that the barber is always working on a customer if there is one in the chair, otherwise the barber is sleeping until a customer arrives.

Advantages of using synchronization mechanisms to solve the Sleeping Barber Problem include:

  1. Efficient use of resources: The use of semaphores or other synchronization mechanisms ensures that resources (e.g., the barber chair and waiting room) are used efficiently, without wasting resources or causing unnecessary delays.
  2. Prevention of race conditions: By ensuring that only one customer is in the barber chair at a time and that the barber is always working on a customer if there is one in the chair, synchronization mechanisms prevent race conditions that could lead to errors or incorrect results.
  3. Fairness: Synchronization mechanisms can be used to ensure that all customers have a fair chance to be served by the barber.

However, there are also some disadvantages to using synchronization mechanisms to solve the Sleeping Barber Problem, including:

  1. Complexity: Implementing synchronization mechanisms can be complex, especially for larger systems or more complex synchronization scenarios.
  2. Overhead: Synchronization mechanisms can introduce overhead in terms of processing time, memory usage, and other system resources.
  3. Deadlocks: Incorrectly implemented synchronization mechanisms can lead to deadlocks, where processes are unable to proceed because they are waiting for resources that are held by other processes.
  4. Overall, the advantages of using synchronization mechanisms to solve the Sleeping Barber Problem generally outweigh the disadvantages, as long as the mechanisms are implemented correctly and efficiently.
     

As you can see from the output, the barber is initially sleeping until the first customer arrives. The customers arrive randomly and wait in the waiting



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads