datav1readers0READER 1READER 2WRITERP0P4P1P3P2PRODUCERslot 0slot 1slot 2CONSUMERempty3full0mutex1ABCDv1v1v2v201234
Front: producer, buffer, consumer and the semaphores empty, full, mutexBack: readers and a writer sharing data; five philosophers sharing five forksTokens: items, reads, a write and forks moving between threadsFront: a producer, a buffer with three slots, a consumer and the semaphores empty, full and mutex. Back left: shared data with its reader count, two readers and a writer. Back right: five philosophers and five forks. Items fill the slots until the producer sleeps; the consumer's post wakes it. Readers share the data; the writer waits for the count to reach 0. Left-first forks deadlock in a circle; lower-first lets philosopher 3 eat.

Producer-consumer

  1. A producer thread makes items and a consumer thread uses them. Between them is a buffer with 3 slots. Semaphore empty counts free slots (3), full counts filled slots (0), and mutex (1) lets one thread touch the buffer at a time.

Readers-writers

Dining philosophers

What happens

;; step 1/11 · pc-setup
the bounded buffer (OSTEP Figure 31.12, CS162 lecture 8)

sem_init(&empty, 0, 3);   /* free slots   */
sem_init(&full,  0, 0);   /* filled slots */
sem_init(&mutex, 0, 1);   /* a lock        */

producer must wait when the buffer is full
consumer must wait when the buffer is empty
only one thread at a time may change the buffer

The mutex is taken only around the buffer itself, after sem_wait(empty) or sem_wait(full). Taking it first and then sleeping on empty or full while holding it deadlocks: the other thread could never get in to post (OSTEP Figure 31.11). This reader-writer lock prefers readers. POSIX pthread_rwlock_rdlock and Linux kernel rw_semaphore are real reader-writer locks; with priority scheduling POSIX lets a reader in only if no writer is waiting, which stops writer starvation.