Classic Synchronization Problems

Producer–consumer, readers–writers, dining philosophers and the sleeping barber — the canonical concurrency puzzles and their correct solutions.

Advanced 3 min readLesson 8 of 16

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.

puttakeProducersbuffer [ ■ ■ ■ □ □ ]capacity NConsumers

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 empty

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.

VariantPolicyRisk
Readers-preferenceNew readers enter while others are readingWriters starve under constant reads
Writers-preferenceOnce a writer waits, new readers queue behind itReaders can starve
Fair (FIFO)Arrival orderLess 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.

f1f2f3f4f0P0P1P2P3P4
Each edge is a fork shared by two philosophers.

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:

FixHowBreaks which condition
Resource orderingAlways pick up the lower-numbered fork firstCircular wait
Waiter / arbitratorAt most 4 philosophers may try at onceCircular wait
Both-or-nothingPick up both forks atomically (or release the left if the right is busy)Hold and wait
Chandy–MisraForks are passed with "dirty/clean" requestsWorks in distributed settings
Resource ordering
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(); }
}

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/Phaser in Java, threading.Barrier in Python.
Key takeaways
  • 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.