Lecture 9 - Synchronization Problems
semaphore chopstick[5]; chopstick[0..4]=1;
while (1) { wait(chopstick[i]); wait(chopstick[(i+1)%5]); /* eat */ signal(chopstick[i]); signal(chopstick[(i+1)%5]); /* think */ }
void philosopher() { think; if (odd(i)) { wait(chopstick[(i+1) % n]); wait(chopstick[i]); } else { wait(chopstick[i]); wait(chopstick[(i+1) % n]); } eat; if (odd(i)) { signal(chopstick[(i+1) % n]); signal(chopstick[i]); } else { signal(chopstick[i]); signal(chopstick[(i+1) % n]); } }
semaphore wrt, mutex; int readcount; wrt=1; mutex=1; readcount=0;
while (1) { wait(wrt); /* perform writing */ signal(wrt); }
while (1) { wait(mutex); readcount++; if (readcount == 1) wait(wrt); signal(mutex); /* perform reading */ wait(mutex); readcount--; if (readcount == 0) signal(wrt); signal(mutex); }
constant CHAIRS = maximum number of chairs (including barber chair) semaphore mutex=1,next_cust=0,barber_ready=0; int cust_count=0;
while (1) { /* live your non barber-shop life until you decide you need a haircut */ wait(mutex); if (cust_count>=CHAIRS) { signal(mutex); exit; /* leave the shop if full, try tomorrow */ } cust_count++; /* increment customer count */ signal(mutex); signal(next_cust); /* wake the barber if he's sleeping */ wait(barber_ready); /* wait in the waiting room */ /* get haircut here */ wait(mutex); cust_count--; /* leave the shop, freeing a chair */ signal(mutex); }
while (1) { wait(next_cust); /* sleep until a customer shows up */ signal(barber_ready); /* tell the next customer you are ready */ /* give the haircut here */ }