Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chai

ID: 3541331 • Letter: T

Question

The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chairs, and the
barber room containing the barber chair. If there are no customers to be served, the barber
goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the
customer leaves the shop. If the barber is busy, but chairs are available, then the customer
sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber.
Write a program to coordinate the barber and the customers.

Explanation / Answer

THIS IS THE WORKING CODE OF SLEEPING BARBE PROBLEM IN C LANGUAGE.

THE CODE IS SIMPLIFIED TO BE MOST BASIC POSSIBLE.

PLEASE DO HAVE A LOOK AT IT AND RATE ME.


#include<stdio.h>

#include<string.h>

#include<pthread.h>

#include<stdlib.h>

#include<unistd.h>

#include<sys/types.h>

#include<semaphore.h>

sem_t barberReady,accessWRSeats,custReady;

int numberOfFreeWRSeats=15,times=7;

pthread_t barber,customer;


void* BarberFunction(void* arg)

{

int value=100;

while(times)

{

sem_wait(&custReady); // try to acquire a customer, if none is available then goes to sleep

sem_getvalue(&custReady,&value);

if(value<=0)

printf("Barber is sleeping as no customers are ready ");

sem_wait(&accessWRSeats);

numberOfFreeWRSeats+=1;

sem_post(&barberReady);

sem_post(&accessWRSeats);

printf("Barber is ready to cut hair ");

times--;

}

return NULL;

}

void* CustomerFunction(void* arg)

{

while(times)

{

sem_wait(&accessWRSeats);

if(numberOfFreeWRSeats>0){

numberOfFreeWRSeats-=1;

sem_post(&custReady);

sem_post(&accessWRSeats);

sem_wait(&barberReady);

printf("Customer got a haircut ");

}

else sem_post(&accessWRSeats);

printf("Customer leaves without a haircut ");

}

return NULL;

}


int main()

{

sem_init(&barberReady,1,0);

sem_init(&accessWRSeats,1,1);

sem_init(&custReady,1,0);

pthread_create(&barber,NULL,&BarberFunction,NULL);

pthread_create(&customer,NULL,&CustomerFunction,NULL);

pthread_join(barber,NULL);

pthread_join(customer,NULL);

return 0;

}


59,1-8 92%

NOTE- Compile this program by

gcc sb.c -o sb -lpthread


View the output by

./sb

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote