7.sleeping Barber Problem
7.sleeping Barber Problem
Description:
The Sleeping Barber Problem is a classic synchronization problem that demonstrates how multiple
threads (customers and a barber) can interact in a shared resource (barber shop with chairs). In this
problem, the barber sleeps until a customer arrives and then serves the customer. The number of chairs
in the waiting room determines how many customers can wait.
In this program:
1. We use three semaphores: customers to signal the presence of customers, barber to signal that
the barber is ready to cut hair, and mutex for mutual exclusion.
2. The barber_thread simulates the barber. It waits for customers to arrive, cuts hair, and sleeps
for a while to simulate hair cutting.
3. The customer_thread simulates customers arriving at the barber shop. If there's a chair
available, the customer takes a seat and waits for the barber. If all chairs are occupied, the
customer leaves.
4. We create and join threads for the barber and customers, and use semaphores to control access
to shared resources.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_CUSTOMERS 10
#define NUM_CHAIRS 5
sem_t customers;
sem_t barber;
sem_t mutex;
int waiting = 0;
int main() {
pthread_t barber_t, customers_t[NUM_CUSTOMERS];
int customer_ids[NUM_CUSTOMERS];
sem_init(&customers, 0, 0);
sem_init(&barber, 0, 0);
sem_init(&mutex, 0, 1);
pthread_join(barber_t, NULL);
for (int i = 0; i < NUM_CUSTOMERS; i++) {
pthread_join(customers_t[i], NULL);
}
sem_destroy(&customers);
sem_destroy(&barber);
sem_destroy(&mutex);
return 0;
}
Output:
Customer 1 takes a seat.
Barber is cutting hair.
Customer 8 takes a seat.
Customer 4 takes a seat.
Customer 2 takes a seat.
Customer 1 is getting a haircut.
Customer 5 takes a seat.
Customer 10 takes a seat.
Customer 7 leaves, no chairs available.
Customer 6 leaves, no chairs available.
Customer 9 leaves, no chairs available.
Customer 3 leaves, no chairs available.
Barber is cutting hair.
Customer 8 is getting a haircut.
Barber is cutting hair.
Customer 4 is getting a haircut.
Barber is cutting hair.
Customer 2 is getting a haircut.
Barber is cutting hair.
Customer 5 is getting a haircut.
Barber is cutting hair.
Customer 10 is getting a haircut.
Result: