In the Sleeping-Barber problem, a barbershop consists of a waiting room with n c
ID: 3583394 • Letter: I
Question
In the Sleeping-Barber problem, a barbershop consists of a waiting room with n chairs and one barber chair. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and the barber is asleep, the customer wakes up the barber. If the barber is busy but chairs are available, then the customer sits in FCFS free chairs. If all chairs are occupied, then the customer is blocked. Using POSIX semaphores, write a program to synchronize the operations of the barber and the customers. Your program should display all barbershop operations.Explanation / Answer
code for sleeping-barber using semaphore
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include <unistd.h>
#include<semaphore.h>
#define n 10 //user can define upto 10 chairs or customers and more than that customer count he will wait in the waiting room
#define n1 50
int status[n];
int b=0;
sem_t mutex;
sem_t barber;
void *barb()
{
printf("Barber is Sleeping ");
b=1;
sem_wait(&barber);
printf("Barber now woke up ");
sleep(1);
b=0;
}
void *handler(void *ptr)
{
int x;
x = *((int *) ptr);
int flag=0;
int i=0;
int count=0;
for(i=0;i<n;i++)
{
if(status[i]==1)
{
flag=1;
count++;
}
}
printf("Count=%d",count);
if(count==n)
{
printf("%d Customer Returned ",x);
return 0;
}
if(flag==1)
{
status[x]=1;
printf("%d Customer waiting ",x);
sem_wait(&mutex);
}
if(b==1)
{
printf("Customer %d woke up barber",x);
sem_post(&barber);
}
printf("Cutting Hair of customer %d ",x);
status[x]=1;
sleep(5);
flag=0;
for(i=0;i<n;i++)
{
if(status[i]==1)
{
flag=1;
}
}
status[x]=0;
printf("Finished cutting Hair of customer %d ",x);
if(flag==1)
sem_post(&mutex);
}
int main()
{
sem_init(&mutex, 0, n);
sem_init(&barber, 0, 1);
pthread_t thread[n1];
pthread_t barber;
int i=0;
for(i=0;i<n;i++)
{
status[i]=0;
}
pthread_create(&barber,NULL,barb,NULL);
pthread_join(barber,NULL);
for(i=0;i<n1;i++)
{
sleep(1);
printf("Customer entered %d ",i);
pthread_create(&thread[i], NULL, handler, (void *)&i);
pthread_join(thread[i],NULL);
}
for(i=0;i<n1;i++)
{
pthread_join(thread[i],NULL);
}
sem_post(&barber);
}