










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











Five philosophers sit around a table with five forks and spaghetti to eat. Philosophers think for a while and they want to eat, only spaghetti, for a while. To eat a philosopher requires two forks, one from the left and one from right. Assume a philo. can only pick up one fork at a time. After eating, forks are placed down and philo. goes back to thinking.
Devise an algorithm that will allow philosophers to eat. Must satisfy mutual exclusion
One solution is to protect obtaining forks with a binary semaphore (mutex)
#define N 5 /* number of philos / #define LEFT (i+N-1)%N / # of i's left / #define RIGHT (i+1)%N / # of i's right / #define THINKING 0 #define HUNGRY 1 #define EATING 2 int state[N]; / keep track of state / semaphore mutex = 1; semaphore s[N]; / semaphore per philo */
void take_forks(int i) { wait(mutex); state[i] = HUNGRY; test(i); // try getting 2 forks signal(mutex); if state[i] != EATING wait(s[i]); // block if no forks acquired }
void test (int i) { if ( state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING ) { state[i] = EATING; signal(s[i]); } }
Another solution is to have some philos be left handed first. Others:
Models access to a database. Some processes want to read the DB others write it. Many readers can read at the same time. But when writing mutual exclusion is needed. Following code could shut out writers if enough readers.
void reader () { while (TRUE) { wait(mutex); rc = rc + 1; if ( rc == 1 ) wait(db); signal(mutex); read_data_base(); wait(mutex); rc = rc โ 1; if ( rc == 0 ) signal(db); signal(mutex); use_data_read(); } }
Barber shop with one barber, one barber chair and N chairs to wait in. When no customers the barber goes to sleep in barber chair and must be woken when a customer comes in. When barber is cutting hair new customers take empty seats to wait, or leave if no vacancy. Program barber and customers so no race condition exists.
#define CHAIRS 5 /* # of chairs */ semaphore customers = 0; semaphore barbers = 0; semaphore mutex = 1; int waiting = 0;
void barber () { while (TRUE) { wait(customers); wait(mutex); waiting = waiting โ 1; signal(barbers); signal(mutex); cut_hair(); } }