Os Lab Assignment 8 U19cs042
Os Lab Assignment 8 U19cs042
A barber shop has a single barber, a single barber’s chair in a small room, and a large waiting room
with n seats. The barber and the barber’s chair are visible from the waiting rooms. After servicing
one customer, the barber checks whether any customers are waiting in the waiting room. If so, he
admits one of them and starts serving him; otherwise, he goes to sleep in the barber’s chair. A
customer enters the waiting room only if there is at least one vacant seat and either waits for the
barber to call him if the barber is busy, or wakes the barber if he is asleep. Identify the
synchronization requirements between the barber and customer processes.
a. Code the barber and customer processes such that deadlocks do not arise.
We use 3 semaphores. Semaphore customers counts waiting customers; semaphore barbers is the
number of idle barbers (0 or 1); and mutex is used for mutual exclusion. A shared data variable
customers1 also counts waiting customers. It is a copy of customers. But we need it here because we
can’t access the value of semaphores directly. We also need a semaphore cutting which ensures that
the barber won’t cut another customer’s hair before the previous customer leaves.
int customer1 = 0;
void barber() {
while(true) {
customers1 = customers1 - 1;
signal(barbers);
signal(mutex);
cut_hair();
void customer() {
if (customers1 < n) {
customers1 = customers1 + 1;
signal(customers);
signal(mutex);
wait(barbers); //wait for available barbers
get_haircut();
else {
signal(mutex);
cut_hair(){
waiting(cutting);}
get_haircut(){
signal(cutting);
there are k barbers and k barber chairs in the barber room, instead of
just one. Write a program to coordinate the barbers and the customers.
// shared data
semaphore waiting_room_mutex = 1;
semaphore barber_room_mutex = 1;
semaphore barber_chair_free = k;
semaphore sleepy_barbers = 0;
int num_waiting_chairs_free = N;
boolean customer_entry( ) {
wait(waiting_room_mutex);
if (num_waiting_chairs_free == 0) {
signal(waiting_room_mutex);
return false;
}
signal(waiting_room_mutex);
wait(barber_chair_free);
wait(waiting_room_mutex);wait(barber_room_mutex);
num_waiting_chairs_free++;
signal(waiting_room_mutex);
int mychair;
mychair = I;
break;
signal(barber_room_mutex);
signal(sleepy_barbers);
wait(barber_chairs[mychair]);
signal(barber_chair_free);
return true;
void barber_enters() {
while(1) {
wait(sleepy_barbers);
// find the customer
wait(barber_room_mutex);
int mychair;
}}