Hello,
Iam trying to implement the sleeping barber problem using semaphores and running on UNIX machine. Iam linking it to the thread libraries :
bash-2.03$ g++ sleepingBarber.cpp -lpthread -o sleeping
but when i execute it i get the following error:
bash-2.03$ sleeping
Starting Program
Segmentation Fault (core dumped)
:
Please Help. Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<synch.h>
#include <pthread.h>
#include<iostream>
#include<pthread.h>
const int totalChairs = 15;
int waiting = 0;
int finished = 0;
//Binary Semaphores - mutex,barber
//Counting Semaphores - customers, cutting
struct semaphores
{
sema_t mutex, barber, customers, cutting;
};
static semaphores * Semaphores;
void cut_hair()
{
//P(cutting)
sema_wait(&(Semaphores->cutting));
}
void get_haircut(int custNum)
{
//V(cutting)
cout<<" BARBER CUTTING HAIR OF CUSTOMER "<<custNum<<endl;
sema_post(&(Semaphores->cutting));
sleep(3);
}
void *Barber(void* ignore)
{
while(!finished)
{
sema_wait(&(Semaphores->customers)); //Sleep if no customers P(Customers)
cout<<" Barber Sleeping!"<<endl;
sema_wait(&(Semaphores->mutex)); //Get access to waiting V(mutex)
waiting--; //Choose a customer
sema_post(&(Semaphores->barber)); //barber busy V(barber)
sema_post(&(Semaphores->mutex)); //Release access to waiting V(mutex)
sleep(3);
cut_hair();
}
}
void *Customer(void *num)
{
int custNum = *(int *)num;
cout<<"Customer "<<custNum<<" Arrives"<<endl;
sema_wait(&(Semaphores->mutex)); //Enter Critical Section P(mutex)
if(waiting < totalChairs)
{
waiting++;
sema_post(&(Semaphores->customers)); //Wake up barber V(Customers)
sema_post(&(Semaphores->mutex)); //Release access to waiting V(mutex)
sema_wait(&(Semaphores->barber)); //Wait if barber busy P(barber)
get_haircut(custNum); //Get in chair be serviced
cout<<"[c] Customer "<<custNum<<" got a haircut"<<endl;
exit(1);
}
else
{
cout<<"[c] Customer "<<custNum<<" Returns as shop is full"<<endl;
sema_post(&(Semaphores->mutex)); //Release access to waiting V(mutex)
exit(1);
}
}
void initializeSemaphores()
{
sema_init(&(Semaphores->mutex),1,USYNC_PROCESS,NULL);
sema_init(&(Semaphores->barber),0,USYNC_PROCESS,NULL);
sema_init(&(Semaphores->customers),0,USYNC_PROCESS,NULL);
sema_init(&(Semaphores->cutting),0,USYNC_PROCESS,NULL);
}
int main()
{
cout<<"Starting Program"<<endl;
//Initialize the semaphores
initializeSemaphores();
pthread_t barberThread,customerThread[totalChairs];
pthread_create(&barberThread, NULL, Barber, NULL);
for (int i=0; i<totalChairs; i++)
{
pthread_create(&customerThread, NULL, Customer, (void *)&i);
}
for (int i=0; i<totalChairs; i++)
{
pthread_join(customerThread,NULL);
}
pthread_join(barberThread,NULL);
finished = 1;
sema_post(&(Semaphores->barber)); // Wake the barber so he will exit.
pthread_join(barberThread,NULL);
}
Really appreciate it.