Producer–consumer problem

Also known as: bounded-buffer problem

On this page 7

The producer–consumer problem, also called the bounded-buffer problem, is the classic concurrency problem of coordinating one or more producer threads that generate data and one or more consumer threads that process it, when both share a fixed-size buffer. A correct solution guarantees that producers never add to a full buffer, consumers never take from an empty one, and no two threads corrupt the buffer by modifying it at the same time.

First formulated by Edsger Dijkstra in the 1960s as a demonstration of semaphores, the problem remains central to concurrency in programming because the same pattern underlies message queues, thread pools, logging pipelines, I/O drivers and stream processing. It is a teaching example and, at the same time, one of the most frequently implemented synchronization structures in production software.

What a correct producer–consumer solution must guarantee

A correct solution must satisfy three distinct conditions at once. Two of them concern capacity, and one concerns the integrity of the shared data structure. Missing any one of them produces a specific class of bug that may appear only under load.

RequirementMeaningFailure if violated
Mutual exclusionOnly one thread modifies the buffer indices at a timeRace condition, lost or duplicated items
No overflowA producer waits while the buffer is fullOverwritten data or unbounded memory growth
No underflowA consumer waits while the buffer is emptyReading stale or invalid data
ProgressWaiting threads resume when the condition changesDeadlock or lost wakeup
Efficient waitingBlocked threads do not consume CPUBusy waiting and wasted cores
Requirements of the bounded-buffer problem

The buffer itself is usually a ring buffer (circular array) with a capacity N, a write index and a read index. The capacity acts as backpressure: when consumers fall behind, producers are slowed down instead of filling memory without limit.

Classic solutions with semaphores and condition variables

The textbook solution uses three semaphores: a counting semaphore empty initialized to N, a counting semaphore full initialized to 0, and a binary semaphore or mutex protecting the buffer. A producer waits on empty, locks the mutex, inserts the item, unlocks and signals full. A consumer performs the mirror sequence.

The order of operations matters. If a producer acquires the mutex before waiting on empty, it can block while holding the lock, and no consumer can ever enter to free a slot. This is a textbook deadlock caused by lock ordering, and it is the most common mistake in handwritten solutions.

In languages based on monitors, the same logic uses one mutex and two condition variables, typically named notFull and notEmpty. Each thread checks its condition in a while loop, not an if, because condition variables permit spurious wakeups and because another thread may consume the slot between the signal and the reacquisition of the lock.

ApproachSynchronization primitivesStrengthsWeaknesses
SemaphoresTwo counting semaphores and a mutexCompact, maps directly to the problemEasy to misorder; errors are silent
Monitor with condition variablesOne mutex, two condition variablesClear structure, standard in Java and C++Requires while loops and careful signaling
Library blocking queueEncapsulated internallyTested, simple to useLess control over policy and memory
Lock-free ring bufferAtomic operations and memory barriersVery low latency, no blockingHard to verify; often limited to one producer and one consumer
ChannelsLanguage runtimeIdiomatic in Go and RustSemantics vary between runtimes
Implementation approaches compared

Variants of the problem

The problem changes character depending on how many producers and consumers share the buffer and whether the buffer is bounded. Specialized data structures exploit these constraints to reduce synchronization cost, so naming the variant precisely is an important design step.

VariantDescriptionSynchronization need
SPSCSingle producer, single consumerLock-free possible with two atomic indices
MPSCMany producers, single consumerContention on the write side only
SPMCSingle producer, many consumersContention on the read side only
MPMCMany producers, many consumersFull synchronization on both ends
Unbounded bufferNo capacity limitNo overflow check, but risk of memory exhaustion
Zero-capacity rendezvousHandoff without storageProducer blocks until a consumer takes the item
Producer–consumer variants and their implications

The SPSC ring buffer is popular in audio processing, network drivers and trading systems because it needs no locks: the producer owns the write index, the consumer owns the read index, and each only reads the other with proper acquire and release ordering.

Designing a producer–consumer pipeline in practice

In real systems, the main design decisions are buffer capacity, the policy when the buffer is full and the shutdown protocol. These choices affect latency, throughput and memory far more than the choice of primitive.

  • Size the buffer to absorb bursts, not to hide a consumer that is permanently slower; a persistent backlog means more consumers or faster processing are needed.
  • Choose a full-buffer policy explicitly: block the producer, fail fast with an error, drop the oldest item or drop the newest item.
  • Define shutdown with a sentinel or a closed flag so consumers exit cleanly instead of waiting forever on an empty buffer.
  • Batch items where possible, because taking ten items per lock acquisition reduces contention considerably.
  • Measure queue depth as a metric; it is the most direct signal of imbalance between producers and consumers.

Most modern standard libraries supply a ready solution, such as BlockingQueue in Java, queue.Queue in Python or buffered channels in Go. Using these is usually the safest recommendation, and a custom implementation is justified only when profiling shows the library queue is the bottleneck.

Typical bugs and how to recognize them

Producer–consumer bugs are notoriously timing-dependent: they often pass unit tests and appear only under production load or on machines with more cores. Knowing the symptoms shortens diagnosis considerably.

SymptomLikely causeFix
All threads hangMutex acquired before the capacity waitWait on capacity first, then lock
Occasional lost itemsUnsynchronized index updateProtect indices with a lock or atomics
Consumer sleeps despite dataLost wakeup from signaling outside the lockSignal under the lock or use while loops
High CPU while idleBusy waiting in a polling loopUse blocking primitives
Memory grows steadilyUnbounded queue with a slow consumerBound the buffer and apply backpressure
Symptoms, causes and fixes

The simple explanation

Picture a bakery with a shelf that holds twelve loaves. Bakers put bread on the shelf, and sales staff take it off for customers. If the shelf is full, the bakers must wait. If it is empty, the sales staff must wait. Two people must not grab the same spot at once.

The producer–consumer problem is about making these rules work for computer programs that run many tasks at the same time. A good solution keeps both sides busy without losing items, without overfilling memory and without everyone getting stuck waiting for each other.

How it is used in practice

A web service writes detailed access logs for every request. Writing directly to disk inside each request handler added several milliseconds of latency under load, because the disk was slower than the request rate during traffic peaks.

The team introduces a bounded queue of 10,000 log entries. Request threads act as producers and only enqueue a small record, which takes microseconds. A single background consumer thread drains the queue in batches of up to 500 entries and writes them to disk in one operation. When a disk stall fills the queue, the chosen policy is to drop new debug-level entries while still blocking briefly for error-level ones. Median request latency falls back to its baseline, and queue depth becomes a monitored metric that alerts the team before the buffer reaches capacity.