Producer-Consumer One common situation: Producers and consumers communicate via a buffer.
Producer() { while (1) { >> P(empty); /* Get an empty buffer (decrease count), block if unavail */ P(mutex); /* acquire critical section: shared buffer */ >> V(mutex); /* release critical section */ V(full); /* increase number of full buffers */ } Producer
Consumer() { while (1) { P(full); P(mutex); <<< critical section: Remove item from shared buffer */ V(mutex); V(empty); } Consumer
Reader-Writer Problem Another common situation: Readers and writers must access a common data structure. Multiple readers are allowed, but only one writer. This solution allows readers to starve writers.
Writer() { while (1) { P(writing); >> V (writing); } Writer
Reader() { while (1) { P(mutex); rd_count++; if (1 == rd_count) P(writing); V(mutex); >> P(mutex) rd_count--; if ( 0 == rd_count) V(writing); V(mutex); } } Reader