The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chai
ID: 3754178 • Letter: T
Question
The Sleeping-Barber Problem. A barbershop consists of a waiting room with n
chairs and the barber room containing the barber chair. If there are no customers
to be served, the barber goes to sleep. If a customer enters the barbershop and all
chairs are occupied, then the customer leaves the shop. If the barber is busy but
chairs are available, then the customer sits in one of the free chairs. If the barber is
asleep, the customer wakes up the barber.
Using the semaphore constructs described in the textbook (and used for solving
other problems) write a program to coordinate the barber and the customers.That
is, write one procedure for the Barber process and one procedure for the customer
process.) [Hint: define the customers, barbers, and mutex semaphores.]
The code can be schematic (just the same as in the lecture). You don’t have to
write the real code.
Explanation / Answer
Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex Seat = 1; /*it will keep the lock on the barbers chair so that only 1 person can sit at a time*/
int FreeSeats = N; /*Initially Available seats are N*/
Barber() {
while(true) {
/* if no customer is there barber goes to sleep */
sem_wait(Customers);
/* Sits on barbers seat now no can can sit on the seat until it's released.*/
sem_wait(Seats);
/* a chair gets free new customer can come and wait*/
FreeSeats++;
/*barber is now ready to cut hair*/
sem_post(Barber);
/* release the mutex on the chair now next customer can sit on the chair.*/
sem_post(Seat);
/* barber is cutting hair.*/
cut_hair();
}
}
Customer() {
while(true) {
/* protects seat so that only 1 customer tries to sit
on the barbers chair .*/
sem_wait(Seat);
if(FreeSeats > 0) {
/* customer is sitting down on the chair now 1 chair is occupied.*/
FreeSeats--;
/* notify the barber new customer has arrived */
sem_post(Customers);
/* once hair cutting is done now release the lock */
sem_post(Seat);
/* wait in the waiting room if barber is busy. */
sem_wait(Barber);
// customer is having hair cut
get_haircut();
} else {
/* release the lock */
sem_post(Seat);
// customer leaves without haircut
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.