The Wayback Machine - https://web.archive.org/web/20240930164602/https://www.geeksforgeeks.org/sleeping-barber-problem-in-process-synchronization/
Open In App

Sleeping Barber problem in Process Synchronization

Last Updated : 13 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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



Similar Reads

Pass the value from child process to parent process
Prerequisite: Pipe() and Fork() Basic Write a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process. Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5. Input: 1 2 3 4 5 Output: 1 2 3 4 5 // C p
2 min read
Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
Minimum spanning Tree (MST) is an important topic for GATE. Therefore, we will discuss how to solve different types of questions based on MST. Before understanding this article, you should understand basics of MST and their algorithms (Kruskal’s algorithm and Prim’s algorithm). Type 1. Conceptual questions based on MST - There are some important pr
5 min read
Problem Solving on Storage Classes and Scoping of Variables
Storage class of variables includes the scope, visibility and life-time which help to trace the existence of a particular variable during the runtime of a program. There exist four types of storage classes in C: auto, register, static and extern. Auto and Register Storage Classes - The scope of variable declared using auto or register storage class
8 min read
Computer Organization | Problem Solving on Instruction Format
Prerequisite - Basic Computer Instructions, Instruction Formats Problem statement: Consider a computer architecture where instructions are 16 bits long. The first 6 bits of the instruction are reserved for the opcode, and the remaining 10 bits are used for the operands. There are three addressing modes: immediate, direct, and register. For immediat
7 min read
Job Sequencing Problem using TreeSet in JAVA
Given an array of jobs where every job has a deadline and associated profit (if the job is finished before the deadline). It is also given that every job takes a single unit of time, so the minimum possible deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time. Examples: Input : Four Jobs with following
3 min read
Puzzle | Data Recovery Problem
Suppose you have three pen drives P1, P2 and P3 each having 1GB capacity. You also have 3 GB of data. You have to divide these data into P1, P2 and P3 such that if any one of the pen drive among P1, P2, P3 got crashed than you should be able to recover all the data from remaining two pen drives. For example - if P1 crashed then you should be able t
2 min read
Problem on Numbers
Question 1 : Find the number of zeroes in 155! Solution: Multiplication of 2x5 results into 10. So number of zeroes depend on the number of pairs of 2 and 5. In any factorial, number of 5’s is lesser than the number of 2’s. So, we need to count the maximum power of 5 in 155! [155/5] + [155/52] + [155/53] =31 + 6 +1 =38 Hence, number of zeroes is 38
5 min read
Problem on HCF and LCM
Question 1: Find the HCF by long division method of two no’s the sequence of quotient from top to bottom is 9, 8, 5 and the last divisor is 16. Find the two no’s. Solution: Start with the divisor and last quotient. Divisor x quotient + remainder = Dividend 16 x 5 + 0 = 80 80 x 8 + 16 = 656 656 x 9 + 80 = 5984 Hence, two numbers are 656 and 5984. Qu
3 min read
Problem on Pipes and Cisterns
Question 1: 9 pumps working 8 hours a day can empty a reservoir in 20 days. How many such pumps needed to empty the same reservoir working 6 hours a day in 16 days. Solution: Apply formula P1D1H1 /W1= P2D2H2/W2 9 x 20 x 8 = P2 x 16 x 6 P2= 15 pumps required Question 2: A leak can empty a completely filled tank in 10 hours. If a tap is opened in com
3 min read
Problem on Time Speed and Distance
Question 1: A racing car covers a certain distance at a speed of 320 km/hr in 5 hours. To cover the same distance in 5/3 hours it must travel at a speed of: Solution: Given Distance is constant. So, Speed is inversely proportional to time. Ratio of time 5 : 5/3 Ratio of time becomes 3 : 1 Then, Ratio of speed 1 : 3 1 unit -> 320 km/hr 3 unit -
6 min read
Problem on Trains, Boat and streams
Question 1: A train passes two bridges of length 1000 m and 600 m in 120 seconds and 80 seconds respectively. The length of the train. Solution: Distance covered in 120 second = 1000 + length of train(l) Distance covered in 80 seconds = 600 + l So, distance covered in 40 seconds = (1000 + l) - (600 + l) = 400 m Speed = 400/40 = 10 m/s Distance cove
6 min read
Prime Subset Product Problem
Given an array arr[] of N integers. The value of a subset of array A is defined as the product of all prime numbers in that subset. If there are no primes in the subset then the value of that subset is 1. The task is to calculate the product of values of all possible non-empty subsets of the given array modulus 100000007.Examples: Input: arr[] = {3
7 min read
How An Online Judge Works And How To Avoid Time Limit Exceeded Problem?
In this article, you will get consent on how an online judge works and this article discusses very frustrating error Time Limit Exceed error that coders get at some point in time while solving the questions at online platforms. The article primarily discusses three things: How does an online judge work?Why do we get TLE?How to avoid TLE?How Does An
4 min read
Total count of sorted numbers upto N digits in range [L, R] (Magnificent necklace combinatorics problem)
Given three integers N, L, and R, the task is to print the total count of ways to form a necklace of at most N pearls such that the values of a pearl lie in the range [L, R] and are in ascending order. Examples: Input: N = 3, L = 6, R = 9Output: 34Explanation:The necklace can be formed in the following ways: The necklaces of length one that can be
8 min read
Travelling Salesman Problem using Hungarian method
A travelling salesman plans to visit N cities in such a way that he visits each city exactly once and return to the city from where he started. The distance between City i and City j is Cij. Find the shortest tour he can take. Note: Travelling from City i to City i is not possible and Cij may not be equal to Cji. Examples: Input: See the routes in
5 min read
Sahil Garg - Geek on the top | "First Solve the Problem, then Write the code"
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks. Sahil Garg is a programming enthusiast since his high school and took competitive programming in his sophomore year in college. Sahil is an MIT, Manipal graduate and seeks to be CEO of his own company. He believes
5 min read
The Lazy Caterer's Problem
Given an integer n, denoting the number of cuts that can be made on a pancake, find the maximum number of pieces that can be formed by making n cuts. Examples : Input : n = 1 Output : 2 With 1 cut we can divide the pancake in 2 pieces Input : 2 Output : 4 With 2 cuts we can divide the pancake in 4 pieces Input : 3 Output : 7 We can divide the panca
4 min read
Puzzles | (Cryptanalysis, Bottles Problem, Dinner Time, Mystery)
Puzzle 1 : (Cryptanalysis) A detective who was mere days away from cracking an international oil smuggling ring has suddenly gone missing. While inspecting his last-known location, officers found a note: 710 57735 34 5508 51 7718. Currently, there are 3 suspects: Bill, John, and Todd. Can you break the detective’s code and find the criminal's name.
2 min read
Josephus Problem Using Bit Magic
The Problem This problem is named after Flavius Josephus a Jewish historian who fought against the Romans. According to Josephus he and his group of Jewish soldiers were cornered & surrounded by the Romans inside a cave, and they choose to murder and suicide inside of surrender and capture. They decided that all the soldiers will sit in a circl
14 min read
Puzzle | Secret Mail Problem
A person 'A' wants to send a secret message to his friend 'B' through a mail, but C (A's friend), whom A does not trust has access to all A's mails. So A puts his message in a box with a lock but A is not allowed to send a key. How can A send his message through securely? Solution: A send the box to B. B can not open it.So ,he can put another lock
1 min read
Route Poisoning and Count to infinity problem in Routing
The main issue with Distance Vector Routing (DVR) protocols is Routing Loops since Bellman-Ford Algorithm cannot prevent loops. This routing loop in the DVR network causes the Count to Infinity Problem. Routing loops usually occur when an interface goes down or two routers send updates at the same time. Counting to infinity problem: So in this exam
3 min read
Shashank Pathak - Geek on the top | Don’t let your mind get diverted to the consequences of not solving a problem
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks. Shashank Pathak had an inclination towards reasoning and puzzles since his childhood and hence started Competitive Programming. He is currently doing his Research Internship at IIT Indore. Shashank is one of the c
10 min read
How to get rid of Java TLE problem
It happens many times that you have written correct Java code with as much optimization as needed according to the constraints. But, you get TLE ????. This happens due to the time taken by Java to take input and write output using Scanner class which is slow as compared to BufferedReader and StringBuffer class. Read in detail about Scanner Class he
5 min read
Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
Ulo Hotels Recruitment Process
About Ulo Hotels : Founded in 2016, Ulo Hotels is a Nex Generation Quality Budget Hotel Chain offering budget-friendly accommodations for guests without compromising Quality and Services. We are building repetitive guests with our quality 5 Bs service like Best in Guest Service & Care, Bed Clean & Comfortable, Budget Friendly & Value, B
2 min read
Cerner Interview Process
Position Software Engineer(1-3 years) 1. HireVue Round 2. Versant Round 3. Technical Round 4. Technical & Managerial Round Hirevue is online video round of 60 minutes. 1. Your introduction. you have to record your answer in 3 minutes. 2. what you do to learn new technology? 3. write a code to print second last word of input string. after code s
1 min read
CGI Recruitment Process (On-Campus 2018)
About Company : CGI Group Inc. (Consultants to Government and Industries), more commonly known as CGI, is a Canadian global information technology (IT) consulting, systems integration, outsourcing, and solutions company founded in 1976 by Serge Godin and André Imbeau headquartered in Montreal, Quebec, Canada. In 2017, CGI ranked #177 in Forbes Top
4 min read
Android Boot Process
Booting Process In computing, booting is starting up a computer or computer appliance until it can be used. It can be initiated by hardware such as a button press, or by software command. After the power is switched on the computer is relatively dumb, and can read only part of its storage called Read-only memory. There a small program is stored cal
4 min read
Process API Updates in Java
By Process API, we can perform any operation related to a process.Suppose if we want the process id of current running process, or we want to create a new process, or want to destroy already running process, or want to find the child and parent processes of current running process, or if we want to get any information regarding a process, then we c
3 min read
How to execute zombie and orphan process in a single program?
Prerequisite: Zombie and Orphan Processes in C Zombie Process: A zombie process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child's exit status. A process that terminates cannot leave the system until its parent accepts its return code. If
2 min read
Article Tags :
Practice Tags :