Classic Synchronization Problems
Producer–consumer, readers–writers, dining philosophers and the sleeping barber — the canonical concurrency puzzles and their correct solutions.
These problems are the "design patterns" of concurrency. Each captures a situation that appears again and again in real systems, and each has well-known pitfalls. Interviewers love them because they test whether you can reason about interleavings.
1. Producer–consumer (bounded buffer)
Producers add items to a fixed-size buffer and consumers remove them. Producers must wait when the buffer is full and consumers when it's empty.
The classic semaphore solution uses three semaphores:
empty = Semaphore(N) # free slots
full = Semaphore(0) # filled slots
mutex = Semaphore(1) # protects the buffer itself
producer: consumer:
wait(empty) wait(full)
wait(mutex) wait(mutex)
buffer.add(item) item = buffer.remove()
signal(mutex) signal(mutex)
signal(full) signal(empty)In practice, use a library blocking queue:
BlockingQueue<Job> q = new ArrayBlockingQueue<>(100);
// producer
q.put(job); // blocks when full
// consumer
Job j = q.take(); // blocks when emptyimport queue
q = queue.Queue(maxsize=100)
q.put(job) # blocks when full
job = q.get() # blocks when empty
q.task_done()// Node streams implement the same idea with backpressure:
// readable.pipe(writable) pauses the producer when the consumer's buffer is full.
import { pipeline } from "node:stream/promises";
await pipeline(source, transform, destination);This pattern is everywhere: thread pools, logging pipelines, Kafka consumers, TCP buffers, Go channels.
2. Readers–writers
Many threads read shared data and a few write it. Readers can share; a writer needs exclusive access.
| Variant | Policy | Risk |
|---|---|---|
| Readers-preference | New readers enter while others are reading | Writers starve under constant reads |
| Writers-preference | Once a writer waits, new readers queue behind it | Readers can starve |
| Fair (FIFO) | Arrival order | Less concurrency |
readers-preference:
reader: lock(m); rc++; if rc == 1: wait(write); unlock(m)
... read ...
lock(m); rc--; if rc == 0: signal(write); unlock(m)
writer: wait(write) ... write ... signal(write)Real-world forms: ReadWriteLock in Java, RwLock in Rust, and databases' shared/exclusive locks. MVCC avoids the problem in databases by letting readers see a snapshot (Concurrency control).
3. Dining philosophers
Five philosophers sit around a table with one fork between each pair. Each needs both neighbouring forks to eat.
The naive solution — "pick up the left fork, then the right" — deadlocks when all five pick up their left fork at once. Every deadlock condition holds, including a circular wait.
Solutions:
| Fix | How | Breaks which condition |
|---|---|---|
| Resource ordering | Always pick up the lower-numbered fork first | Circular wait |
| Waiter / arbitrator | At most 4 philosophers may try at once | Circular wait |
| Both-or-nothing | Pick up both forks atomically (or release the left if the right is busy) | Hold and wait |
| Chandy–Misra | Forks are passed with "dirty/clean" requests | Works in distributed settings |
void dine(int i, ReentrantLock[] forks) {
int a = i, b = (i + 1) % forks.length;
ReentrantLock first = forks[Math.min(a, b)], second = forks[Math.max(a, b)];
first.lock();
try {
second.lock();
try { eat(i); } finally { second.unlock(); }
} finally { first.unlock(); }
}def dine(i, forks):
a, b = i, (i + 1) % len(forks)
first, second = forks[min(a, b)], forks[max(a, b)]
with first, second: # acquired in a global order
eat(i)// The same principle applies to async locks: acquire in a global order.
async function dine(i: number, forks: Mutex[]) {
const [a, b] = [i, (i + 1) % forks.length].sort((x, y) => x - y);
await forks[a].run(() => forks[b].run(async () => eat(i)));
}4. Sleeping barber
A barber sleeps when there are no customers. Arriving customers wake the barber, wait in one of N chairs, or leave if all chairs are full. It models a server with a bounded waiting queue that rejects overflow: exactly a thread pool with a bounded queue and a rejection policy, or a web server returning 503 when overloaded.
5. Cigarette smokers and barriers
- Cigarette smokers shows that some problems can't be solved with semaphores alone if the agent can't be modified; it needs helper threads.
- Barrier: N threads must all reach a point before any continues (parallel phases in simulations). Use
CyclicBarrier/Phaserin Java,threading.Barrierin Python.
- Producer–consumer: counting semaphores for slots and items plus a mutex, or simply a blocking queue.
- Readers–writers: shared reads, exclusive writes; choose a policy to avoid starvation.
- Dining philosophers: naive locking deadlocks; global lock ordering fixes it.
- Sleeping barber: a bounded queue with rejection — the model for server overload handling.
- Use library primitives (blocking queues, RW locks, barriers) rather than hand-rolled semaphores.