Producer-consumer separates the threads that create work from the threads that do it. The two sides share a bounded buffer: producers put items in and block while it is full, consumers take items out and block while it is empty. Neither side knows how many of the other there are or how fast they run. It is behind every blocking queue, thread pool, Unix pipe and Go channel, and getting it right comes down to one lock, two conditions and a while loop.
Think of it like
A sushi conveyor with a few plates
The chefs (producers) put plates on a short conveyor and the diners (consumers) take them off. When every spot on the belt is taken, a chef waits instead of stacking plates on the floor. When the belt is empty, diners wait instead of grabbing at nothing. A chef who has been waiting for a free spot looks again before putting a plate down, because another chef may have filled the spot first. That last habit is the while loop this lesson is about.
The problem
Two producer threads make items (P1 makes a1 and a2, P2 makes b1 and b2) and two consumer threads process them (C1 and C2 take two items each). They meet in a buffer of two slots, a ring with head, tail and count. A careful first version protects the buffer with a lock and uses two condition variables so threads can sleep instead of spinning: notFull for producers, notEmpty for consumers. This is the Before version in the visualizer above.
class BoundedBuffer {
private final String[] buf = new String[2];
private int head, tail, count;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
void put(String x) throws InterruptedException {
lock.lock();
try {
if (count == buf.length) notFull.await();
buf[tail] = x;
tail = (tail + 1) % buf.length;
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
}
String take() throws InterruptedException {
lock.lock();
try {
if (count == 0) notEmpty.await();
String x = buf[head];
head = (head + 1) % buf.length;
count--;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}It looks right, and most of the time it works: under the visualizer's Producers first and Fair round robin schedules every item is taken exactly once. The flaw is in what happens between a signal and the moment the woken thread runs again. await() releases the lock while the thread sleeps, and a signal only makes the sleeper eligible to run: before await() can return, it has to get the lock back, and any other thread may get there first.
- Taking from an empty buffer. Pick The race: C1 finds the buffer empty and waits. P1 puts
a1and signals, which wakes C1. But C2 locks first, seescountis 1 and takesa1. When C1 finally re-acquires the lock, itsifdoes not look atcountagain, so it reads slot 1, which was never written: it getsnullandcountbecomes -1 (step 14). - Putting into a full buffer. Pick Overflow race: P1 finds the buffer full and waits. C1 takes
a1and signals. P2 locks first and fills the free slot withb2. P1 wakes, skips the check, and writesa2overb1, which nobody had taken:b1is lost andcountis 3 in a buffer of 2 (step 21). - Spurious wakeups. Java, POSIX threads and C++ all allow a waiting thread to wake up with no signal at all. With an
if, that thread also runs on as if the condition were true. - No lock at all is worse. Without the lock,
if (count == 0)and the read after it are a check-then-act race: two consumers can both seecount == 1and both take the same item, and two producers can both write into the same slot.
The pattern
Intent: let threads that produce work and threads that consume it run at their own pace by passing items through a shared bounded buffer, where producers block while it is full and consumers block while it is empty. It is the classic bounded-buffer problem, which Edsger Dijkstra used in the 1960s to show how semaphores coordinate processes.
- Producer
- A thread that creates items (requests, log lines, tasks) and calls
put(). Here P1 and P2. - Consumer
- A thread that calls
take()and processes each item. Here C1 and C2. Each item goes to exactly one consumer. - Bounded buffer (blocking queue)
- The shared storage with a fixed capacity N. Here a ring:
buf[N],head(next slot to read),tail(next slot to write) andcount. Its capacity is what limits how far producers can get ahead. - Lock (mutex)
- Makes each
put()andtake()a critical section: only the thread holding it may read or changehead,tail,countor the slots. - Condition variables (
notFull,notEmpty) - Wait sets attached to the lock.
await()atomically releases the lock and puts the thread to sleep;signal()wakes one sleeper, which must re-acquire the lock beforeawait()returns. A signal with nobody waiting does nothing: it is not saved for later. - Guard (
while) - The condition a thread waits for, checked in a loop:
while (count == N) notFull.await();. The thread re-checks after every wake-up and only proceeds when the condition is true while it holds the lock.
What the visualizer shows
- Steps: the visualizer runs both versions on a simulated scheduler. Each step is one atomic action of one thread (lock, check, the critical section, wait, re-acquire, unlock), so you see exactly where threads interleave.
- Invariants: three checks run after every step: never over capacity, never takes from empty, no item lost or duplicated. A broken one turns rose, with the step it broke at and why.
- Bounded buffer: the two slots with
headandtailunder them,count, and the items put and taken so far. A slot whose item was already taken keeps its old value, struck through: that is what a carelesstake()reads. - Locks and conditions: who holds
lock, who is blocked on it, who was woken and wants it back, and who is asleep onnotFullornotEmpty. - Threads over time: one lane per thread, one column per step. Amber is a step running, sky blue a thread that wants the lock (blocked, or woken and waiting to re-acquire it), violet a thread asleep on a condition, green a finished thread. The code panel marks the line each thread is at.
- Schedules: Producers first and Fair round robin are ordinary schedules; The race and Overflow race pick the order that breaks the Before version; Seeded random draws one (press Reshuffle for another); Manual lets you choose which thread runs next. The Pick next buttons take over from the step on screen at any time.
Walkthrough
- 1
P1 fills the buffer (steps 1 to 8)
With With blocking queue and Producers first selected, P1 locks, checks
count == N(0, so there is room), storesa1in slot 0 and unlocks; then the same fora2in slot 1. Each put also signalsnotEmpty, but nobody is waiting yet, so nothing happens. - 2
P2 finds it full and waits (steps 9 to 11)
P2 locks and checks:
countis 2, the buffer is full.notFull.await()releases the lock and P2 sleeps innotFull's wait set. Its lane turns violet. - 3
C1 makes room and signals (steps 12 to 14)
C1 locks, sees two items and takes
a1. ItsnotFull.signal()wakes P2, but P2 cannot continue yet: C1 still holds the lock. P2's lane turns sky blue. - 4
C1 takes a2 and finishes (steps 15 to 19)
C1 unlocks and runs on: it locks again and takes
a2before P2 is scheduled. That is fine; P2 is woken but simply has not run yet. - 5
C2 finds it empty and waits (steps 20 to 22)
C2 locks, sees
count == 0and waits onnotEmpty, releasing the lock. - 6
P2 re-acquires the lock and checks again (steps 23 to 25)
P2 gets the lock back and its
await()returns. Because of thewhile, it checkscount == Nagain before touching the buffer:countis 0, so it storesb1and signalsnotEmpty, which wakes C2. - 7
Everyone finishes (steps 26 to 38)
P2 puts
b2. C2 re-acquires the lock, checkscount == 0again (now 2) and takesb1andb2. Each item was taken exactly once and the three invariants held at every step. - 8
Now the race
Choose The race. In the Before version C1 takes from the empty buffer at step 14. With the blocking queue, the same schedule makes C1 check again at step 14, find
count == 0, and go back to sleep at step 15; it gets a real item later and all 48 steps keep every invariant.
Before and after
Before: if
- Checks the condition once, before the first wait
- A woken thread assumes the condition still holds
- Breaks when another thread gets the lock first, or on a spurious wakeup
- Fails only under some interleavings: tests usually pass
- Symptoms:
nullitems, lost items,countbelow 0 or above N
With blocking queue: while
- Checks the condition every time the thread wakes up
- Proceeds only when the condition is true while holding the lock
- Correct under every interleaving, spurious wakeups included
- Costs one extra check per wake-up
- Usually you do not write it at all: you use the library's blocking queue
| Schedule | Before (if) | With blocking queue (while) |
|---|---|---|
| Producers first | All invariants hold (36 steps) | All invariants hold (38 steps) |
| Fair round robin | All invariants hold (42 steps) | All invariants hold (44 steps) |
| The race | Never takes from empty breaks at step 14: C1 gets null, count is -1 | C1 checks again at step 14 and waits; all hold (48 steps) |
| Overflow race | Never over capacity breaks at step 21: b1 is overwritten, count is 3 | P1 checks again and waits; all hold (41 steps) |
The schedules that break the Before version are not exotic. Both are a signal followed by another thread winning the lock, which on a busy machine happens all the time. An exhaustive search of every interleaving of this four-thread program, run in the tests behind the visualizer, finds violating schedules in the Before version and none, and no deadlock, in the version with while. The visualizer's code panel leaves out try/finally and InterruptedException to stay short; real code needs both, as above.
Variations
Why while, not if
A condition variable tells a thread that the condition might have become true, never that it is true now. Three things can happen between the signal and the moment the woken thread holds the lock again: another thread gets the lock first and changes the state (the visualizer's races), a broadcast wakes several threads but only the first can proceed, or the thread wakes spuriously. The Java documentation of Object.wait says to always wait in a loop for this reason, and C++ builds the loop in: cv.wait(lock, [&] { return count > 0; }) is exactly while (!(count > 0)) cv.wait(lock);.
Signal or broadcast
| Wakes | Java | C++ | POSIX |
|---|---|---|---|
| One waiter (signal) | notify(), signal() | notify_one() | pthread_cond_signal |
| Every waiter (broadcast) | notifyAll(), signalAll() | notify_all() | pthread_cond_broadcast |
signal() and signalAll() are the methods of Java's Condition; notify() and notifyAll() belong to every object's built-in monitor.With two conditions, as here, a signal always reaches a thread waiting for exactly the change that just happened: a put frees a consumer, a take frees a producer, and one item or one free slot can satisfy only one waiter. So one signal is enough, and ArrayBlockingQueue works this way. Java's built-in monitors (synchronized with wait/notify) have only one wait set per object, so producers and consumers wait together. Then notify() can wake the wrong kind of thread: a consumer's signal wakes another consumer, which finds the buffer still empty and waits again, and with an unlucky sequence every thread ends up asleep. With a single wait set, use notifyAll(). Broadcast is always safe with while loops, but it wakes every waiter to compete for the lock (a thundering herd), so prefer separate conditions and signal when you can.
Sizing the buffer
A buffer absorbs bursts; it cannot fix a consumer that is slower on average. If producers make 100 items a second and consumers handle 80, any bounded buffer fills up and producers then run at 80 a second, and an unbounded one grows until memory runs out. Size the buffer for the bursts you expect, not for the total. A bigger buffer also means more latency: by Little's law an item waits about as long as the queue length divided by the rate at which consumers drain it, so 10,000 queued items at 1,000 a second is a 10-second delay. A capacity of a few times the number of consumers is a common starting point; measure from there. Beware of unbounded defaults: Executors.newFixedThreadPool(n) in Java uses an unbounded LinkedBlockingQueue, so if tasks arrive faster than workers finish them, nothing pushes back and the queue grows until the process runs out of memory.
Backpressure: what to do when the buffer is full
- Block (
put): the producer slows down to the consumers' pace. This is backpressure, and it is the default of the pattern. - Wait a while, then give up (
offer(x, 100, MILLISECONDS)in Java,put(x, timeout=0.1)in Python): the producer can report "busy" instead of hanging. - Reject at once (
offer(x)returnsfalse,put_nowaitraisesqueue.Full): load shedding, as in Backpressure & Load Shedding. - Drop or replace: keep only the newest sample (sensor readings, mouse positions) or drop the oldest.
- Run it yourself: Java's
ThreadPoolExecutor.CallerRunsPolicymakes the submitting thread run the task, which naturally slows submission down.
Shutting down: the poison pill
Real consumers loop forever, so how do they stop? A poison pill is a special item that means "no more work". When every producer has finished (join them first), put one pill per consumer; a consumer that takes a pill exits. Because the queue is FIFO, every real item put before the pills is processed first. The implementations below do this. Alternatives: Go closes the channel (close(ch), and for x := range ch ends), Java's ExecutorService.shutdownNow() interrupts workers blocked in take(), and Python 3.13 added Queue.shutdown().
Other shapes
- One producer, one consumer: the buffer can be lock-free, a ring where only the producer moves
tailand only the consumer moveshead(with atomic loads and stores). The LMAX Disruptor is a well-known high-performance design built on a ring buffer. - Capacity zero: a rendezvous, where
putwaits until a consumer takes the item. Java'sSynchronousQueueand Go's unbuffered channels work this way. - Semaphores instead of conditions: Dijkstra's version uses a semaphore counting empty slots, one counting full slots, and a mutex.
putacquires an empty slot, stores, and releases a full one;takedoes the opposite. - Pipelines: each stage consumes from one queue and produces into the next (parse, then resize, then upload). The slowest stage sets the throughput, and bounded queues between stages keep a fast stage from flooding a slow one.
In real code
| Where | What | Notes |
|---|---|---|
| Java | BlockingQueue: ArrayBlockingQueue, LinkedBlockingQueue, SynchronousQueue, PriorityBlockingQueue | put/take block; offer/poll with a timeout give up. ArrayBlockingQueue is a ring guarded by one ReentrantLock with notEmpty and notFull conditions, the design in this lesson; LinkedBlockingQueue uses separate locks for putting and taking |
| Java executors | ThreadPoolExecutor | Its work queue is a BlockingQueue<Runnable>: the submitting threads produce tasks and the pool's workers consume them (see Thread Pool) |
| Python | queue.Queue(maxsize) | Built on threading.Conditions that share one lock (not_empty, not_full); maxsize <= 0 means unbounded; task_done() and join() wait until every item has been processed. asyncio.Queue is the coroutine version |
| Go | Channels: make(chan T, n) | A buffered channel is a bounded blocking queue built into the language: sends block while it is full, receives while it is empty; close ends the range loops of the receivers |
| Rust | std::sync::mpsc::sync_channel(n) | Bounded: send blocks while the buffer is full; a bound of 0 makes a rendezvous channel |
| Node.js | Streams | Backpressure without threads: write() returns false once the buffered data reaches highWaterMark, and the producer should wait for the drain event |
| Unix shells | Pipes: producer | consumer | The kernel's pipe buffer is the bounded queue: a writer blocks when it is full (64 KiB by default on Linux) and a reader blocks when it is empty |
| Between services | Message brokers (Kafka, RabbitMQ, SQS) | The same pattern across machines, with persistence and acknowledgements: see Message Queues & Pub/Sub and Competing Consumers |
BlockingQueue<String> queue = new ArrayBlockingQueue<>(100);
// producer thread
queue.put(order); // blocks while 100 items are waiting
// consumer thread
String next = queue.take(); // blocks while the queue is empty
// give up instead of blocking forever
if (!queue.offer(order, 50, TimeUnit.MILLISECONDS)) {
rejectAsBusy(order);
}When to use it, and when not to
Reach for producer-consumer when
- Work is created and processed at different, varying rates
- Slow processing (I/O, image work) must not hold up the thread that receives requests
- You want a fixed number of workers no matter how much work arrives
- Stages of a pipeline should run in parallel
- Producers must slow down, not crash the process, when consumers fall behind
Think twice when
- The caller needs the result right away: a direct call is simpler (or a future, see Future & Promise)
- Every consumer must see every item: that is publish/subscribe, not a shared queue
- Items must be processed in strict order across several consumers
- The work must survive a crash or a deploy: an in-memory queue loses it; use a broker
- Handing an item over costs more than processing it: batch items, or skip the queue
Producer-consumer vs similar patterns
| Pattern | Who gets an item | Buffer | Typical setting |
|---|---|---|---|
| Producer-consumer | Exactly one consumer | Bounded queue; producers block when it is full | Threads in one process |
| Thread Pool | One worker thread | The pool's task queue (a producer-consumer inside) | Running many small tasks on a few threads |
| Publish/Subscribe | Every subscriber of the topic | Per subscriber, usually in a broker | Events across modules or services |
| Observer | Every observer, called directly | None: the subject calls each observer in turn | In-process notifications, usually synchronous |
| Active Object | The object's own thread | A queue of method calls in front of one object | Making an object's methods run asynchronously |
| Queue-Based Load Leveling | One consumer service | A message queue between services | Smoothing bursts between systems |
Implementation
The visualizer's program as a complete, runnable demo: a ring buffer of 2 slots with a lock and the conditions notFull and notEmpty, waits in while loops, two producers putting a1, a2 and b1, b2, and two consumers. When both producers are done, main puts one poison pill per consumer so they exit. Java uses ReentrantLock with Condition, Python threading.Condition, C++ std::mutex with std::condition_variable. JavaScript has no shared-memory threads by default (worker_threads with SharedArrayBuffer and Atomics exist, but most code runs on one event loop), so the TypeScript version is a bounded async queue: put and take return promises that wait instead of blocking a thread. It still needs the while loop, because another put can fill the free slot before a woken producer resumes.
import threading
class BoundedBuffer:
def __init__(self, capacity):
self._items = [None] * capacity
self._head = self._tail = self._count = 0
self._lock = threading.Lock()
# Two conditions that share one lock.
self._not_full = threading.Condition(self._lock)
self._not_empty = threading.Condition(self._lock)
def put(self, x):
with self._lock:
while self._count == len(self._items):
self._not_full.wait()
self._items[self._tail] = x
self._tail = (self._tail + 1) % len(self._items)
self._count += 1
self._not_empty.notify()
def take(self):
with self._lock:
while self._count == 0:
self._not_empty.wait()
x = self._items[self._head]
self._items[self._head] = None
self._head = (self._head + 1) % len(self._items)
self._count -= 1
self._not_full.notify()
return x
POISON = object() # tells a consumer to stop
print_lock = threading.Lock()
def produce(buf, items):
for x in items:
buf.put(x)
def consume(buf, name):
while True:
x = buf.take()
if x is POISON:
return
with print_lock:
print(f"{name} took {x}")
if __name__ == "__main__":
buf = BoundedBuffer(2)
consumers = [
threading.Thread(target=consume, args=(buf, name))
for name in ("C1", "C2")
]
producers = [
threading.Thread(target=produce, args=(buf, items))
for items in (["a1", "a2"], ["b1", "b2"])
]
for t in consumers + producers:
t.start()
for t in producers:
t.join()
for _ in consumers:
buf.put(POISON) # one poison pill per consumer
for t in consumers:
t.join()
print("done")Key takeaways
- Producer-consumer decouples the threads that make work from the threads that do it through a bounded buffer: producers block while it is full, consumers block while it is empty.
- The classic implementation is one lock and two condition variables (
notFull,notEmpty):await()releases the lock while sleeping and must re-acquire it before it returns. - Always wait in a
whileloop. A signal only means the condition might be true; in the visualizer, oneiflets C1 take from an empty buffer and P1 overwrite an item nobody had taken. - Signal is enough with separate conditions; with a single wait set (Java's
wait/notify) use broadcast (notifyAll), or a thread can wake the wrong kind of waiter and everyone sleeps. - The bound is the point: a full buffer pushes back on producers. Size it for bursts, and decide whether producers block, time out or drop when it is full.
- Stop consumers with a poison pill per consumer (or by closing the channel), and in real code use the library's blocking queue.
Common pitfalls
- Waiting with
ifinstead ofwhile: a thread woken by a signal, by a broadcast or spuriously runs on even though another thread already changed the buffer. - Checking the condition outside the lock: the state can change between the check and the wait, and a signal sent in that gap is lost, so the waiter may sleep forever (a lost wakeup).
- Using
notify()with one shared wait set for producers and consumers: it can wake a thread of the wrong kind, leaving every thread waiting. - Using an unbounded queue (like the default in
Executors.newFixedThreadPool): when consumers fall behind, memory and latency grow until the process fails. - Forgetting how consumers stop: blocked in
take()forever, they keep the program from exiting. Send one poison pill per consumer after every producer has finished, or close the channel.
Interview tips
- When asked to implement a blocking queue, write the fields first (array, head, tail, count, lock, two conditions), then
putandtakewithwhileloops,unlockinfinally, and say why each part is there. - Expect the follow-ups: why
whileand notif,signalvssignalAll, what happens when the queue is full (block, time out, reject), and how to shut consumers down. - Connect it to systems you know: a thread pool's task queue, Go channels, Unix pipes, and message brokers between services are all producer-consumer with different buffers.
Real-world applications
- Thread pools and executors: submitting threads produce tasks, worker threads consume them from a blocking queue.
- Logging: application threads enqueue log records and a background thread writes them to disk or the network, so a slow disk does not stall requests.
- Media and data pipelines: download, decode, resize and upload stages connected by bounded queues.
- Servers: an acceptor thread hands connections or requests to a pool of handler threads.
- Shells and streams:
producer | consumerpipes, and stream backpressure in Node.js.
Test yourself
In the visualizer's Before version, C1 is woken by P1's signal, but C2 locks first and takes a1. What does C1 do when it gets the lock back?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.