Homework 3 Solutions ECE 426 Spring 2018 Gabriel Kuri

2 Problems - 50 pts total

1 (25 pts) The sleeping barber problem is a classic problem, where a barber shop has one barber, one barber chair, and n chairs for waiting customers, if any, to sit and wait. If there are no customers present, the barber sits down in the barber chair and sleeps. When a customer arrives, he has to wake up the sleeping barber. If additional customers arrive while the barber is cutting a customer’s hair, they either sit down (if there are empty chairs) or leave the shop (if all chairs are full). Consider a slight modification to the classic problem, where there are m barbers and m chairs at the barber shop, instead of just one. Write a program in C or pseudocode using semaphores to implement this problem (with m barbers and m barber chairs).

1 waiting room mutex = 1 ; 2 semaphore barber room mutex = 1 ; 3 semaphore barber c h a i r f r e e = k ; 4 semaphore sleepy b a r b e r s = 0 ; 5 semaphore barber c h a i r s [ k ] = {0 , 0 , 0 , . . . } ; 6 i n t barber c h a i r s t a t e s [ k ] = {0 , 0 , 0 , . . . } ; 7 i n t num w a i t i n g c h a i r s f r e e = N; 8 boolean customer entry ( ) { 9 // try to make it into waiting room 10 wait(waiting room mutex ) ; 11 i f (num w a i t i n g c h a i r s f r e e == 0) { 12 signal(waiting room mutex ) ; 13 r e t u r n false; 14 } 15 n u m w a i t i n g c h a i r s f r e e −−;// grabbeda chair 16 signal(waiting room mutex ) ; 17 // now, wait until there isa barber chair free 18 wait(barber c h a i r f r e e ) ; 19 //a barber chair is free, so release waiting room chair 20 wait(waiting room mutex ) ; 21 wait(barber room mutex ) ; 22 n u m w a i t i n g c h a i r s f r e e ++; 23 signal(waiting room mutex ) ; 24 25 // now graba barber chair 26 i n t mychair; 27 f o r(int I=0; I

1 47 wait(sleepy b a r b e r s ) ; 48 // find the customer 49 wait(barber room mutex ) ; 50 i n t mychair; 51 f o r(int I=0; I

2 (25 pts) Recall the readers-writers problem from class, how can we efficiently synchronize multiple readers and writers such that multiple readers can read together but a writer gets exclusive access? Implement a solution to this problem by writing a program in C or pseudocode. Ensure the readers are not starved of access due to priority of the writers and vice versa.

Writer:

1 wait ( wrt ) ; 2 ... 3 writing is performed 4 ... 5 signal(wrt);

Reader:

1 wait(mutex) ; 2 readcount := readcount + 1; 3 i f readcount = 1 then wait(wrt); 4 signal(mutex); 5 ... 6 reading is performed 7 ... 8 wait(mutex) ; 9 readcount := readcount − 1 ; 10 i f readcount = 0 then signal(wrt); 11 signal(mutex);

2