Producer-consumer, readers-writers and dining philosophers
About this lesson
Three famous puzzles show up again and again in real programs. A producer and a consumer share a small buffer. Many readers and an occasional writer share some data. Five philosophers share five forks. Watch each one run step by step: semaphores count free and filled slots, a reader count lets readers share while a writer waits, and a fixed lock order breaks a deadly circle of waiting. The lessons on semaphores and monitors build the tools used here, and the Software lesson on threads and concurrency shows the race they prevent.
A buffer between two threads
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.
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
Read the lesson step by step
A buffer between two threads
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.
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 bufferPutting an item
To put item A, the producer calls sem_wait(empty): 3 becomes 2, so a slot is reserved. It takes the mutex, writes A into slot 0, gives the mutex back, then calls sem_post(full): 0 becomes 1. One item is ready.
producer, one item (C99, POSIX semaphores): sem_wait(&empty); empty 3 -> 2 (would sleep at 0) sem_wait(&mutex); mutex 1 -> 0 (lock) buf[in] = 'A'; slot 0 = A in = (in + 1) % 3; sem_post(&mutex); mutex 0 -> 1 (unlock) sem_post(&full); full 0 -> 1The buffer fills up
The producer puts B and C the same way. Now empty is 0 and full is 3. For item D, sem_wait(empty) finds 0, so the producer is put to sleep. It does not spin or overwrite a slot: it waits.
item empty full slots A 2 1 A _ _ B 1 2 A B _ C 0 3 A B C D sem_wait(&empty) finds 0: the producer sleeps sem_wait(3): if the value is above zero, decrement and return; otherwise block until the decrement becomes possibleTaking wakes the producer
The consumer calls sem_wait(full): 3 becomes 2. It takes A from slot 0 under the mutex, then calls sem_post(empty). That post wakes the sleeping producer, which puts D into the freed slot 0.
consumer empty full slots sem_wait(&full) 0 2 A B C take A (under the mutex) 0 2 _ B C sem_post(&empty) 1 2 wakes the producer producer finishes its wait 0 2 puts D, sem_post(&full) 0 3 D B C the whole program (C99, POSIX; build with -pthread): #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <semaphore.h> #include <stdio.h> #define SLOTS 3 #define ITEMS 4 static char buf[SLOTS]; static int in, out; static sem_t empty, full, mutex; static void *producer(void *arg) { (void)arg; for (int i = 0; i < ITEMS; i++) { sem_wait(&empty); /* wait for a free slot */ sem_wait(&mutex); buf[in] = (char)('A' + i); in = (in + 1) % SLOTS; sem_post(&mutex); sem_post(&full); /* one more filled slot */ } return NULL; } static void *consumer(void *arg) { (void)arg; for (int i = 0; i < ITEMS; i++) { sem_wait(&full); /* wait for a filled slot */ sem_wait(&mutex); char c = buf[out]; out = (out + 1) % SLOTS; sem_post(&mutex); sem_post(&empty); /* one more free slot */ putchar(c); } putchar('\n'); return NULL; } int main(void) { pthread_t p, c; sem_init(&empty, 0, SLOTS); /* 0: shared by threads */ sem_init(&full, 0, 0); sem_init(&mutex, 0, 1); pthread_create(&p, NULL, producer, NULL); pthread_create(&c, NULL, consumer, NULL); pthread_join(p, NULL); pthread_join(c, NULL); return 0; } prints ABCDMany readers at once
Readers only look at the shared data, so any number may read together. The first reader in locks writers out; later readers just add 1 to the count. Here two readers read v1 at once, and readers = 2.
a simple reader-writer lock (OSTEP Figure 31.13): typedef struct { sem_t lock; /* guards readers */ sem_t writelock; /* one writer or many readers */ int readers; } rwlock_t; static void read_lock(rwlock_t *rw) { sem_wait(&rw->lock); if (++rw->readers == 1) sem_wait(&rw->writelock); /* first in */ sem_post(&rw->lock); } static void read_unlock(rwlock_t *rw) { sem_wait(&rw->lock); if (--rw->readers == 0) sem_post(&rw->writelock); /* last out */ sem_post(&rw->lock); } static void write_lock(rwlock_t *rw) { sem_wait(&rw->writelock); } static void write_unlock(rwlock_t *rw) { sem_post(&rw->writelock); } R1 read_lock readers 1 first in: takes writelock R2 read_lock readers 2 just countsA writer waits its turn
A writer changes the data, so it needs it alone. It waits on the write lock. Each reader that leaves subtracts 1, and the last one out, at readers = 0, unlocks. Only then does the writer write v2.
W write_lock readers 2 writelock is held: W sleeps R1 read_unlock readers 1 still not 0 R2 read_unlock readers 0 last out: sem_post(writelock) W wakes, writes data v1 -> v2 (alone) the same lock as a whole program (C99, POSIX): #define _POSIX_C_SOURCE 200809L #include <semaphore.h> #include <stdio.h> typedef struct { sem_t lock; /* guards readers */ sem_t writelock; /* one writer or many readers */ int readers; } rwlock_t; static void read_lock(rwlock_t *rw) { sem_wait(&rw->lock); if (++rw->readers == 1) sem_wait(&rw->writelock); /* first in */ sem_post(&rw->lock); } static void read_unlock(rwlock_t *rw) { sem_wait(&rw->lock); if (--rw->readers == 0) sem_post(&rw->writelock); /* last out */ sem_post(&rw->lock); } static void write_lock(rwlock_t *rw) { sem_wait(&rw->writelock); } static void write_unlock(rwlock_t *rw) { sem_post(&rw->writelock); } int main(void) { rwlock_t rw = { .readers = 0 }; sem_init(&rw.lock, 0, 1); sem_init(&rw.writelock, 0, 1); read_lock(&rw); read_lock(&rw); printf("readers = %d\n", rw.readers); read_unlock(&rw); read_unlock(&rw); write_lock(&rw); printf("writer in, readers = %d\n", rw.readers); write_unlock(&rw); return 0; } prints readers = 2 writer in, readers = 0Writers can starve
In this simple lock a new reader may join whenever the count is above 0. If readers keep overlapping, the count never reaches 0 and the writer waits forever: starvation. Fairer locks hold new readers back while a writer waits.
readers over time 1 2 1 2 1 2 1 2 1 writer still waiting: yes OSTEP: "it would be relatively easy for readers to starve writers" POSIX pthread_rwlock_rdlock (with priority scheduling): a reader gets in only if no writer holds the lock and no writer is blocked on it Linux kernel: rw_semaphore and rwlock_t are "multiple readers and single writer" locksFive philosophers, five forks
Five philosophers sit at a round table with one fork between each pair. To eat, philosopher p needs both forks beside it: left fork p and right fork (p + 1) mod 5. Each fork is a lock that only one may hold.
Dijkstra, 1971 (EWD310): spaghetti eaten "with two forks" int left(int p) { return p; } int right(int p) { return (p + 1) % 5; } philosopher left fork right fork P0 0 1 P1 1 2 P2 2 3 P3 3 4 P4 4 0 neighbours share a fork, so they cannot eat at the same timeEveryone grabs left
Suppose all five pick up their left fork at the same moment. Every fork is now held, and each philosopher waits for its right fork, held by its neighbour. The waiting forms a circle, so nobody can ever eat: deadlock.
void get_forks(int p) { /* broken */ sem_wait(&forks[left(p)]); sem_wait(&forks[right(p)]); } fork 0 held by P0 P0 waits for fork 1 (P1) fork 1 held by P1 P1 waits for fork 2 (P2) fork 2 held by P2 P2 waits for fork 3 (P3) fork 3 held by P3 P3 waits for fork 4 (P4) fork 4 held by P4 P4 waits for fork 0 (P0) P0 -> P1 -> P2 -> P3 -> P4 -> P0 a circle of waiting eating: nobodyBreak the circle
The fix: always pick up the lower-numbered fork first. Philosopher 4 needs forks 4 and 0, so it reaches for fork 0 first and loses it to philosopher 0. Fork 4 stays free, so philosopher 3 takes it and eats.
lock ordering: every thread takes locks in one fixed order P4 needs forks 4 and 0: it takes 0 first (OSTEP Figure 31.16) fork 0 held by P0 fork 1 held by P1 fork 2 held by P2 fork 3 held by P3 fork 4 held by P3 eating: P3 P4 holds nothing, so it blocks nobody a runnable version with pthread mutexes as forks (C99, POSIX): #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> #define N 5 #define MEALS 10000 static pthread_mutex_t fork_[N]; static int meals[N]; static void *philosopher(void *arg) { int p = *(int *)arg; int l = p, r = (p + 1) % N; int first = l < r ? l : r, second = l < r ? r : l; /* lower first */ for (int m = 0; m < MEALS; m++) { pthread_mutex_lock(&fork_[first]); pthread_mutex_lock(&fork_[second]); meals[p]++; /* eat */ pthread_mutex_unlock(&fork_[second]); pthread_mutex_unlock(&fork_[first]); } return NULL; } int main(void) { pthread_t t[N]; int id[N]; for (int i = 0; i < N; i++) pthread_mutex_init(&fork_[i], NULL); for (int i = 0; i < N; i++) { id[i] = i; pthread_create(&t[i], NULL, philosopher, &id[i]); } for (int i = 0; i < N; i++) pthread_join(t[i], NULL); for (int i = 0; i < N; i++) printf("%d ", meals[i]); printf("\n"); return 0; } prints 10000 10000 10000 10000 10000 (it always finishes)Three patterns, one toolbox
Each problem stands for a real pattern: a queue between threads, data read far more often than written, and several locks taken together. Counting semaphores, a reader count and one fixed lock order solve them.
the bounded buffer with real Python threads: import threading SLOTS = 3 buf = [None] * SLOTS empty = threading.Semaphore(SLOTS) # free slots full = threading.Semaphore(0) # filled slots mutex = threading.Lock() got = [] def producer(items): for i, item in enumerate(items): empty.acquire() # sleeps while the buffer is full with mutex: buf[i % SLOTS] = item full.release() def consumer(n): for i in range(n): full.acquire() # sleeps while the buffer is empty with mutex: got.append(buf[i % SLOTS]) empty.release() items = "ABCDEFGH" threads = [threading.Thread(target=producer, args=(items,)), threading.Thread(target=consumer, args=(len(items),))] for t in threads: t.start() for t in threads: t.join() print("".join(got)) prints ABCDEFGH
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01In the bounded buffer with 3 slots, what are the starting values of the semaphores empty, full and mutex?
empty counts free slots, so it starts at 3. full counts filled slots, so it starts at 0. mutex is a lock, a semaphore that starts at 1 so exactly one thread can hold it.
02The buffer is full (empty = 0) and the producer calls sem_wait(&empty). What happens?
sem_wait only decrements a value above zero; otherwise it blocks. The consumer's sem_post(&empty) after taking an item wakes the producer, which then completes its wait and puts the item.
03Why may many readers hold a reader-writer lock at once, but only one writer?
Reads alone never conflict. A write in the middle of a read, or two writes at once, could leave the data half changed. So the first reader locks writers out and the last reader out lets them in.
04In the simple reader-writer lock, how can a writer starve?
The write lock is only released when the last reader leaves. If a new reader always joins before the old one leaves, that moment never comes. Fairer locks stop new readers while a writer is waiting.
05Five philosophers each need forks p and (p + 1) mod 5. Which rule prevents deadlock?
If all take left first (or all right first), all five can hold one fork and wait in a circle. With the lower-numbered fork first, philosopher 4 reaches for fork 0 before fork 4, so the circle cannot close and someone can always eat.
Glossary
- Semaphore
- A counter shared by threads with two operations: wait (sem_wait) takes 1 if the count is above 0 and otherwise sleeps; post (sem_post) adds 1 and wakes a sleeping waiter.
- Bounded buffer
- A fixed-size queue between threads. Producers put items in and consumers take them out; producers must wait when it is full and consumers when it is empty.
- Mutex
- A lock that only one thread can hold at a time. A semaphore that starts at 1 works as one.
- Reader-writer lock
- A lock with two modes: many readers may hold it together, or one writer alone.
- Starvation
- A thread waits forever because others keep getting the resource first, even though the system as a whole keeps working.
- Deadlock
- A set of threads each waiting for something another one in the set holds, so none of them can ever continue.
- Lock ordering
- Giving all locks a fixed order and always taking them in that order. It makes a circle of waiting, and so this kind of deadlock, impossible.
Notes and sources
- 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).
- When sem_post wakes a sleeping thread, the woken thread completes its own decrement. The figure shows empty going 0, 1, 0 in one moment; which thread actually runs next is up to the scheduler.
- Unnamed POSIX semaphores (sem_init) work on Linux. macOS declares sem_init but does not implement it, so on a Mac use named semaphores (sem_open) or Grand Central Dispatch semaphores to run the C example.
- 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.
- Edsger Dijkstra set the dining philosophers problem in 1971 (EWD310). Taking forks in one global order is the general cure for this kind of deadlock; the Deadlock module looks at it, and other cures, in depth.
- Lock ordering prevents deadlock, but on its own it does not promise that every philosopher eats often: a slow philosopher can still keep losing a fork to its neighbours.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 31: Semaphores (bounded buffer, reader-writer locks, dining philosophers)
- E. W. Dijkstra, EWD310: Hierarchical ordering of sequential processes (the five dining philosophers)
- Berkeley CS162, Lecture 8: Synchronization 2 (bounded buffer with semaphores)
- Berkeley CS162, Lecture 9: Semaphores, Monitors and Readers/Writers
- MIT 6.1810 (2024), lecture notes: Locking (deadlock and lock ordering)
- Linux man-pages: sem_wait(3)
- Linux man-pages: sem_post(3)
- Linux man-pages: sem_init(3)
- POSIX via Linux man-pages: pthread_rwlock_rdlock(3p)
- Linux kernel documentation: Lock types and their rules
- Python documentation: threading (Semaphore objects)
Quiz Unlocks after the last step.