





















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!






















Binary vs. Counting Semaphores
Semaphores can implement Mutex
Bounded Buffer using Semaphores int BB[N]; int count, head, tail = 0; Semaphore_t m; // value initialized to 1 Semaphore_t empty; // value initialized to N Semaphore_t full; // value initialized to 0 Append(int elem) { P(empty); P(m); BB[tail] = elem; tail = (tail + 1)%N; count = count + 1; V(m); V(full); } int Remove () { P(full); P(m); int temp = BB[head]; head = (head + 1)%N; count = count - 1; V(m); V(empty); return(temp); }
Readers-writers using Semaphores Database db; int nreaders = 0; Semaphore_t m; // value initialized to 1 Semaphore_t wrt; // value initialized to 1 Reader() { P(m); nreaders++; if (nreaders == 1) P(wrt); V(m); …. Read db here … P(m); nreaders--; if (nreaders == 0) V(wrt); V(m); } Writer() { P(wrt); … Write db here … V(wrt); }
within a critical section (using say P(mutex)/V(mutex)) can avoid the deadlock.
int state[N]; Semaphore_t s[N]; // init. to 0 Semaphore_t mutex; // init. to 1 #define LEFT (i-1)%N #define RIGHT (i+1)%N philosopher(i) { while () { take_forks(i); eat(); put_forks(i); think(); } } take_forks(i) { P(mutex); state[i] = HUNGRY; test(i); V(mutex); P(s[i]); } put_forks(i) { P(mutex); state[i] = THINKING; test(LEFT); test(RIGHT); V(mutex); } test(i) { /* can phil i eat? if so, signal that philosopher */ if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; V(s[i]); } }