#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
// number of chairs in waiting room
#define NUM_CHAIRS 3
// shared data
int waiting = 0; // number of customers waiting
int is_sleeping = 1;
// semaphores
sem_t barber_ready;
pthread_mutex_t waiting_mutex;
// function prototypes
void *barber(void *_);
void *customer(void *_);
int main()
{
srand(time(NULL));
// initialize semaphores
sem_init(&barber_ready, 0, 0);
pthread_mutex_init(&waiting_mutex, NULL);
// create barber thread
pthread_t b_thread;
pthread_create(&b_thread, NULL, barber, NULL);
// create customer threads
while (1)
{
// simulate a random delay before new customer arrives
sleep(rand() % 5 + 1);
pthread_t c_thread;
pthread_create(&c_thread, NULL, customer, NULL);
}
return 0;
}
void *barber(void *_)
{
while (1)
{
pthread_mutex_lock(&waiting_mutex);
int customers_waiting = waiting;
pthread_mutex_unlock(&waiting_mutex);
if (customers_waiting > 0)
{
// Customer is waiting, so wake up the barber
is_sleeping = 0;
sem_post(&barber_ready);
// Simulate hair cutting
printf("Barber: cutting hair...\n");
sleep(rand() % 3 + 1);
printf("Barber: finished cutting hair, ready for another customer.\n");
pthread_mutex_lock(&waiting_mutex);
waiting--; // decrease the number of customers waiting
pthread_mutex_unlock(&waiting_mutex);
}
else
{
printf("Barber: no customers, going to sleep...\n");
is_sleeping = 1;
sleep(1);
}
}
pthread_exit(NULL);
}
void *customer(void *_)
{
// Create a unique ID for this customer
unsigned long id = pthread_self();
// Enter the waiting room
pthread_mutex_lock(&waiting_mutex);
if (waiting < NUM_CHAIRS)
{
printf("Customer %lu: arrived and waiting.\n", id);
waiting++; // increase the number of customers waiting
pthread_mutex_unlock(&waiting_mutex);
if (!is_sleeping)
{
printf("Customer %lu: waking up the barber.\n", id);
}
// Wait for the barber to be ready
sem_wait(&barber_ready);
// Get the hair cut
printf("Customer %lu: getting a haircut.\n", id);
}
else
{
printf("Customer %lu: no vacant chairs, leaving...\n", id);
pthread_mutex_unlock(&waiting_mutex);
}
pthread_exit(NULL);
}