In: Computer Science
using 2 semaphores and 1 mutex: (solve in simple c++ language for linux terminal and add comments please)
The barber shop has one barber (a thread), one barber chair, and n chairs for waiting customers (semaphore), if any, to sit on. If there are no customers (each customer is a thread) present, the barber sits down in the barber chair and falls asleep. When a customer arrives, he has to wake up the sleeping barber. If additional customers arrive while the barber is cutting a customer's hair, they either sit down (if there are empty chairs) or leave the shop (if all chairs are full). The problem is to program the barber and the customers without getting into race conditions.
Solution:
Sleeping Barber Problem :
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> #include<errno.h> #include<sys/ipc.h> #include<semaphore.h> #define N 5 time_t end_time; sem_t mutex,customers,barbers; //Three semaphors int count=0; // number of customers waiting for haircuts void barber(void *arg); void customer(void *arg); int main(int argc,char *argv[]) { pthread_t id1,id2; int status=0; end_time=time(NULL)+20; //Barber Shop Hours is 20 seconds //Semaphore initialization sem_init(&mutex,0,1); sem_init(&customers,0,0); sem_init(&barbers,0,1); //Barber thread initialization status=pthread_create(&id1,NULL,(void *)barber,NULL); if(status!=0) perror("create barbers is failure!\n"); //Customer thread initialization status=pthread_create(&id2,NULL,(void *)customer,NULL); if(status!=0) perror("create customers is failure!\n"); //Customer_thread first blocked pthread_join(id2,NULL); pthread_join(id1,NULL); exit(0); } void barber(void *arg) //Barber Process { while(time(NULL)<end_time || count>0) { sem_wait(&customers); sem_wait(&mutex); count--; cout<<"Barber:cut hair,count is:\n"<<count; sem_post(&mutex); sem_post(&barbers); sleep(3); } } void customer(void *arg) //Customers Process { while(time(NULL)<end_time) { sem_wait(&mutex); if(count<N) { count++; cout<<"Customer:add count,count is:\n"<<count; sem_post(&mutex); sem_post(&customer); sem_wait(&barbers); } else //If the number is full of customers,just put the mutex lock let go sem_post(&mutex); sleep(1); } }