In: Computer Science
Sleeping Barber Problem where there is only 1 barber in the shop for x clients
function Customer()
acquire(mutex)
if num_waiting < num_chairs then
num_waiting + 1
release(customer)
release(mutex)
acquire(barber)
Cutmyhair()
else
release(mutex)
end
end
function Barber()
while not breaking
acquire(customer)
acquire(mutex)
num_waiting - 1
release(barber)
release(mutex)
Clipaway()
end while
end
QUESTION: come up with the pseudocode for the clipaway() and cutmyhair() methods so that each client pays for there haircut and the barber gives each client a customized haircut.
Any language.
thank you in advance !!!
The algorithm for the sleeping barber problem in process synchronisation can be completed as follows:
Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex Seats = 1;
int FreeSeats = N;
Barber {
while(true) {
/* waits for a customer (sleeps). */
down(Customers);
/* mutex to protect the number of available seats.*/
down(Seats);
/* a chair gets free.*/
FreeSeats++;
/* bring customer for haircut.*/
up(Barber);
/* release the mutex on the chair.*/
up(Seats);
/* barber is cutting hair.*/
}
}
Customer {
while(true) {
/* protects seats so only 1 customer tries to sit
in a chair if that's the case.*/
down(Seats); //This line should not be here.
if(FreeSeats > 0) {
/* sitting down.*/
FreeSeats--;
/* notify the barber. */
up(Customers);
/* release the lock */
up(Seats);
/* wait in the waiting room if barber is busy. */
down(Barber);
// customer is having hair cut
} else {
/* release the lock */
up(Seats);
// customer leaves
}
}
}
Also, here is the running code of the problem in C++.
#define CHAIRS 5 // number of chairs for waiting customers
typedef int semaphore;
semaphore customers = 0; // number of waiting customers
semaphore barbers = 0; // number of barbers waiting for customers
semaphore mutex = 1; // for mutual exclusion
int waiting = 0; // customers are waiting not being haircut
void Barber(void)
{
while(true)
{
down(customers); // go to sleep if number of customers is down to 0
down(mutex); // acquire access to 'waiting'
waiting--; //decrement count of waiting customers
up(barbers); // one barber is now ready to cut hair
up(mutex); // release 'waiting'
cut_hair(); //cut hair , non-CS
}
}
void customer(void)
{
down(mutex); // enters CS
if(waiting < CHAIRS)
{
waiting++; // increment count of waiting customers
up(customers); // wake up barber if necessary
up(mutex); // release access to 'waiting'
down(barbers); // wait if no free barber
get_haircut(); // non-CS
}
else
{
up(mutex); // shop is full, do not wait
}
}
Please upvote if you find the answer helpful.