Classic Concurrency Problems
Producer–consumer (bounded buffer), readers–writers, dining philosophers, sleeping barber, H2O and print-in-order — the problems interviewers use to test synchronization, with working solutions.
These problems are the "LeetCode" of concurrency. Each one isolates a pattern you'll meet in real systems: work queues, read-mostly caches, lock ordering, rendezvous.
1. Producer–consumer (bounded buffer)
Producers add items to a fixed-size buffer; consumers remove them. Producers must wait when it's full, consumers when it's empty. This is every work queue, channel, log shipper and thread pool you'll ever use.
With semaphores
#define N 5
int buf[N], in = 0, out = 0;
sem_t empty, full; // sem_init(&empty, 0, N); sem_init(&full, 0, 0);
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void produce(int item) {
sem_wait(&empty); // 1. wait for a free slot (BEFORE the mutex!)
pthread_mutex_lock(&m); // 2. exclusive access to indices
buf[in] = item; in = (in + 1) % N;
pthread_mutex_unlock(&m);
sem_post(&full); // 3. announce a filled slot
}
int consume(void) {
sem_wait(&full);
pthread_mutex_lock(&m);
int item = buf[out]; out = (out + 1) % N;
pthread_mutex_unlock(&m);
sem_post(&empty);
return item;
}
With a monitor (mutex + condition variables)
class BoundedBuffer<T> {
private final Object[] items;
private int head, tail, count;
BoundedBuffer(int cap) { items = new Object[cap]; }
public synchronized void put(T x) throws InterruptedException {
while (count == items.length) wait(); // buffer full
items[tail] = x; tail = (tail + 1) % items.length; count++;
notifyAll(); // wake consumers
}
@SuppressWarnings("unchecked")
public synchronized T take() throws InterruptedException {
while (count == 0) wait(); // buffer empty
T x = (T) items[head]; items[head] = null;
head = (head + 1) % items.length; count--;
notifyAll(); // wake producers
return x;
}
}
// In Go the buffered channel IS a bounded blocking queue.
jobs := make(chan Job, 5)
go func() { for _, j := range work { jobs <- j }; close(jobs) }() // producer
for j := range jobs { process(j) } // consumer
2. Readers–writers
Readers can share; writers need exclusivity.
Reader-preference solution
import threading
class RWLock:
def __init__(self):
self.readers = 0
self.count_lock = threading.Lock() # protects self.readers
self.resource = threading.Lock() # held by a writer, or by the group of readers
def acquire_read(self):
with self.count_lock:
self.readers += 1
if self.readers == 1:
self.resource.acquire() # first reader locks out writers
def release_read(self):
with self.count_lock:
self.readers -= 1
if self.readers == 0:
self.resource.release() # last reader lets writers in
def acquire_write(self):
self.resource.acquire()
def release_write(self):
self.resource.release()
Problem: a steady stream of readers keeps readers > 0 forever → writers starve.
Fair variant
Add a "turnstile" lock that every reader and writer must pass through on entry. A waiting writer holds the turnstile, so newly arriving readers queue behind it:
class FairRWLock(RWLock):
def __init__(self):
super().__init__()
self.turnstile = threading.Lock()
def acquire_read(self):
with self.turnstile: # blocks while a writer is waiting
pass
super().acquire_read()
def acquire_write(self):
self.turnstile.acquire() # stop new readers
self.resource.acquire() # wait for current readers to leave
def release_write(self):
self.resource.release()
self.turnstile.release()
3. Dining philosophers
Five philosophers, five forks between them; each needs both neighbouring forks to eat.
import threading, time, random
N = 5
forks = [threading.Lock() for _ in range(N)]
def philosopher(i, meals=3):
left, right = i, (i + 1) % N
first, second = min(left, right), max(left, right) # resource ordering
for _ in range(meals):
time.sleep(random.random() / 10) # think
with forks[first]:
with forks[second]:
print(f"P{i} eats") # eat
threads = [threading.Thread(target=philosopher, args=(i,)) for i in range(N)]
for t in threads: t.start()
for t in threads: t.join()
Other fixes: allow only N−1 philosophers at the table (semaphore), or pick up both forks atomically inside a monitor.
4. Sleeping barber
A barber sleeps when no customers; customers wait in a room with k chairs or leave if it's full. Models a server with a bounded request queue that sheds load when full.
import threading
CHAIRS = 3
customers = threading.Semaphore(0) # waiting customers
barber_ready = threading.Semaphore(0)
mutex = threading.Lock()
waiting = 0
def barber():
global waiting
while True:
customers.acquire() # sleep until a customer arrives
with mutex:
waiting -= 1
barber_ready.release() # call the next customer to the chair
print("cutting hair")
def customer(i):
global waiting
with mutex:
if waiting == CHAIRS:
print(f"customer {i} leaves (shop full)") # load shedding
return
waiting += 1
customers.release() # wake the barber
barber_ready.acquire() # wait for the chair
print(f"customer {i} gets a haircut")
5. Ordering puzzles (LeetCode concurrency)
| Problem | Pattern |
|---|---|
| Print in order (first, second, third) | two semaphores/events initialised to 0 |
| Print FooBar alternately | two semaphores passing a baton |
| Zero, even, odd | three semaphores, a coordinator hands the baton to the right worker |
| Building H₂O | semaphores limiting 2 H and 1 O, plus a barrier of 3 |
| Fizz Buzz multithreaded | one condition variable; each thread waits until the current number is "its" kind |
class Foo:
def __init__(self):
self.done1 = threading.Event()
self.done2 = threading.Event()
def first(self, f):
f(); self.done1.set()
def second(self, f):
self.done1.wait(); f(); self.done2.set()
def third(self, f):
self.done2.wait(); f()
6. Barriers and latches
- CountDownLatch (one-shot): main thread waits until N workers call
countDown(). - CyclicBarrier / Barrier (reusable): N threads wait for each other at the end of each phase.
- WaitGroup (Go):
Add,Done,Wait.
How to approach these in an interview
- Identify the shared state and the invariants (count ≤ capacity; at most one writer).
- Identify who waits for what — each "wait for" becomes a condition variable or semaphore.
- Write the happy path, then check every interleaving at the boundaries (empty/full, first/last reader).
- Check for deadlock (lock ordering, waiting while holding a lock) and starvation.
- Mention the library primitive you'd use in production (
BlockingQueue, channels,ReadWriteLock).
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.