Classic Concurrency Problems

Producer-consumer, readers-writers and dining philosophers: each problem run as real threads, the failure reproduced, and the standard fixes compared.

Overview

Three problems from the 1960s and early 1970s still carry most concurrency interviews. Each one isolates a single hazard. Producer-consumer is about waiting: a buffer that can be full or empty. Readers-writers is about fairness: sharing without starving anyone. Dining philosophers is about deadlock: several threads each holding one resource and wanting another.

Interviewers use them because the solutions are short and the mistakes are specific. Knowing the problem is not enough; you are expected to write the solution, explain which condition for deadlock or starvation it breaks, and test it.

Producer-consumer

Producers put items into a fixed-size buffer; consumers take them out. A producer must wait when the buffer is full, a consumer when it is empty, and the buffer itself must never be changed by two threads at once.

The semaphore solution uses three objects. The semaphore empty counts free slots and starts at the capacity. The semaphore full counts filled slots and starts at 0. A mutex guards the buffer itself.

Each side follows the same three moves, mirrored. A producer first waits on empty for a free slot, then locks the mutex, appends and unlocks, then signals full. A consumer first waits on full for an item, then locks the mutex, pops and unlocks, then signals empty. The mutex is held only for the short buffer update, never while waiting.

The order matters. If a producer took the mutex first and then waited on empty while the buffer was full, it would sleep holding the mutex, and no consumer could get in to make room. Here is that wrong order, step by step.

  • The producer takes the mutex. The buffer is full.
  • The producer waits on empty, still holding the mutex.
  • A consumer waits for the mutex so it can pop an item.
  • The producer waits forever and so does the consumer: deadlock.

In practice, a blocking queue (queue.Queue(maxsize), Java's ArrayBlockingQueue) gives you this behavior, packaged (built from a lock and conditions rather than semaphores); the Thread-Safe Queue topic builds one from a lock and two condition variables.

Interview questions

  • Walk through the producer-consumer solution with a bounded buffer.
  • How do you solve the dining philosophers problem without deadlock?
  • In readers-writers, how do you stop writers from starving?
  • Make two threads print in strict alternation: ping, pong, ping, pong.

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio