Search

Search papers and lessons

Producer-Consumer Problem

Level 2 · 11 min read

Producer-consumer is a pattern where one thread adds items to a fixed-size buffer and another removes them, and the buffer's size and locks keep the two from overwriting or losing work.

On this page

  • Colour = topic mix
  • Systems
  • ReadReady to readNot yet

TL;DR

The producer-consumer problem is about two threads that share a buffer: a producer adds items to it and a consumer removes them. The buffer has a fixed number of slots, so the producer must wait when it is full and the consumer must wait when it is empty. Getting this right means every item is handed over exactly once, and no two threads ever change the buffer at the same moment.

Builds on: Thread, Mutual Exclusion, Semaphore · Leads to: Buffer Pool

Where it's used

Video and audio playback. A decoder thread turns compressed data into frames and a display thread shows them. A short buffer of frames between the two smooths out bursts in decoding speed, and the same pattern keeps playback from stuttering.

Log and event pipelines. A web server's request handlers write log lines into a buffer and a background thread writes them to disk in batches. The handlers rarely wait for the slow disk, and they block only if the buffer fills. The buffer's size caps how much memory the backlog can use.

Print spoolers and task queues. Applications put jobs into a queue, and worker threads take them out. The queue's length is the bound that stops a flood of jobs from using all memory, and it is the same idea as a bounded buffer.

How it works

The buffer is an array of 2 slots, and we track two counts with semaphores: empty (free slots) and full (filled slots). Starting state: empty = 2, full = 0. There is also a mutex, a lock that only one thread may hold while it touches the array. Each side also keeps a position in the array. The producer's position moves forward one slot per item and wraps from the last slot back to slot 0, and the consumer's position does the same. This is a circular buffer.

  1. The producer makes item x. It first waits until a slot is free: empty goes from 2 to 1. It takes the lock, puts x in slot 0, and releases the lock. Then it raises full from 0 to 1. Check: the buffer holds [x, _], with one free slot.
  2. The producer makes item y. Same steps: empty goes from 1 to 0, y goes in slot 1, full goes from 1 to 2. Check: the buffer is now [x, y] and empty is 0.
  3. The producer makes item z and must wait. It tries to wait for a free slot, but empty is 0, so it blocks. It does not spin in a loop burning CPU: the operating system switches its core to another thread (a context switch) until the consumer wakes it. Check: no item is written, so nothing is overwritten.
  4. The consumer takes an item. It waits until a filled slot exists: full goes from 2 to 1. It takes the lock, removes x from slot 0, and releases the lock. Then it raises empty from 0 to 1. Check: the buffer is [_, y] and empty is 1.
  5. The waiting producer wakes. Raising empty releases the producer that blocked in step 3. It takes the lock, puts z in slot 0, where the producer's position now points, and raises full. Check: the buffer is [z, y] and every item so far has been written exactly once.
  6. Everything is handed over in order. The consumer's position is at slot 1, so it reads y there, then moves on to slot 0 and reads z. Check: the output is x, y, z, the same order the producer used.

The two counts are the whole trick. Each side waits on one count and signals the other, so neither side can run past the buffer's limits, and the lock keeps the array consistent while each side is moving items in or out.

flowchart LR
  P[producer] -->|wait empty, lock, write, unlock, signal full| B[(buffer: N slots)]
  B -->|wait full, lock, read, unlock, signal empty| C[consumer]

The math

Step 1 in symbols: the two counts

Let N be the number of slots. Let e be the number of empty slots and f the number of full slots. Whenever no thread is partway through an operation,

e+f=N,0≤e≤N,0≤f≤Ne + f = N, \qquad 0 \le e \le N, \qquad 0 \le f \le N

The semaphores keep this true between operations. In the middle of one, for example after the producer has taken a slot but before it raises f, the sum is one less than N. The producer's wait decreases e and the consumer's signal increases e, and the opposite holds for f.

Steps 1 and 4 in symbols: each action moves the counts

A producer action changes the state as

e→e−1,f→f+1e \to e - 1, \qquad f \to f + 1

and a consumer action changes it as

f→f−1,e→e+1f \to f - 1, \qquad e \to e + 1

Both moves keep e + f = N. In the trace above, the buffer started with e = 2 and f = 0, and the state after step 2 is e = 0, f = 2, which still sums to 2.

Step 3 in symbols: blocking

A producer is blocked exactly when e = 0. A consumer is blocked exactly when f = 0. A blocked thread waits until the other side raises the count it needs: the consumer's raise of e in step 4 wakes a blocked producer, and the producer's raise of f in step 1 wakes a blocked consumer.

Worked examples

Example
Tiny: a buffer of 1 slot

Take N = 1, with e = 1 and f = 0 at the start.

  1. The producer adds a. It waits for e to be at least 1: e becomes 0. It writes a. It raises f: f becomes 1.
  2. Check the invariant: e + f = 0 + 1 = 1 = N.
  3. The producer tries to add b. It waits for e to be at least 1, but e is 0, so it blocks.
  4. The consumer removes a. It waits for f to be at least 1: f is 1, so it proceeds and drops f to 0. It raises e to 1.
  5. Check: e + f = 1 + 0 = 1 = N. The blocked producer can now write b.
  6. Interpretation: with one slot, the producer and consumer strictly alternate, and each item is seen exactly once.
Example
Standard: a buffer of 5 slots after a partial run

Take N = 5, starting with e = 5 and f = 0. The producer adds 3 items and the consumer removes 1.

  1. Three producer actions each lower e by 1 and raise f by 1. After them, e = 5 minus 3 = 2 and f = 0 plus 3 = 3.
  2. Check: e + f = 2 + 3 = 5 = N.
  3. One consumer action lowers f by 1 and raises e by 1. Now f = 3 minus 1 = 2 and e = 2 plus 1 = 3.
  4. Check: e + f = 3 + 2 = 5 = N.
  5. Interpretation: 2 items are waiting in the buffer, and 3 slots are free for the producer. The producer is still allowed to run, because it has not reached 0 free slots.
Example
Realistic: a decoder feeding a display through an 8-frame buffer

A decoder thread produces 60 frames per second into a buffer of N = 8 frames. A display thread consumes 30 frames per second. The buffer starts empty.

  1. The net rate at which the buffer fills is 60 minus 30 = 30 frames per second.
  2. The buffer is full when f reaches 8. At a net gain of 30 frames per second, that happens after 8 divided by 30, about 0.267 seconds.
  3. After that point the producer blocks, and it can only add a frame when the display removes one. The producer then runs at 30 frames per second, matching the consumer.
  4. Check: at steady state the buffer stays nearly full, and the decoder waits on the display, not the other way round.
  5. Interpretation: a buffer of 8 frames gives about a quarter of a second of slack. A short hiccup in decoding, under that length, does not cause a visible stall.

Try it: A decoder produces 100 items per second, a consumer takes 40 per second, and the buffer has N = 4 slots and starts empty. After how many seconds does the producer first block? Answer: the net fill rate is 100 minus 40 = 60 items per second, so the buffer is full after 4 divided by 60, which is about 0.067 seconds, or 67 milliseconds.

Common mistakes and tradeoffs

It is tempting to think that one lock is enough, because the buffer is the only shared mutable state. In fact a single lock keeps the array consistent, but without counts the producer does not know when to wait for a free slot, and the consumer does not know when to wait for an item. The lock protects the data, and the semaphores express the waiting.

It is tempting to think that a producer can check "is the buffer full?" and then write, in two separate steps. In fact another thread can change the buffer between the check and the write, which is a Race Condition. The wait on the count must be the thing that reserves the slot, so the check and the claim happen as one step.

It is tempting to think that a bigger buffer always helps. In fact a bigger buffer smooths out short bursts, but it also holds more work in memory and delays the consumer's view of the data. It cannot fix a consumer that is slower than the producer on average, because the buffer simply fills and the producer blocks anyway.

When to use it: a steady stream of items between two threads that run at different speeds, where bursts are short.

When not to use it: a single thread that can just call the function directly, or pipelines where the consumer must see items instantly and bursts cannot be absorbed.

Alternatives: an unbounded queue, which never blocks the producer but can grow without limit, and message passing through channels, which hides the locks inside a library.

History

In the mid-1960s Edsger Dijkstra was working on how to coordinate concurrent processes in a shared system. He introduced the semaphore as a way to count available resources and block threads that could not proceed, and the bounded-buffer problem was one of the standard examples he used to show it. The pattern caught on because it turned the question of "how do two threads share data safely" into a small set of operations that operating systems and language libraries could implement once and reuse. Today it appears in kernels, in streaming systems, and in most message queues.

Recap

  • A producer and a consumer share a buffer of N slots, tracked by a count of free slots and a count of filled slots.
  • The producer waits on the free-slot count and signals the filled-slot count; the consumer does the reverse.
  • A lock guards the array itself, so each read or write of a slot happens without interference.
  • Every item is written once and read once, in order, and the sum of free and filled slots equals N whenever no operation is in progress.
  • Read next: Buffer Pool for the same idea applied to memory pages, and Race Condition for why the check and the claim must be one step.

Check yourself

QuestionWhy does the producer wait on the free-slot count before taking the lock, and not after?Show answer

Waiting first means the producer blocks without holding the lock. If it held the lock while waiting for a free slot, the consumer could never take the lock to remove an item, and both threads would be stuck. The lock is only held for the short time the array is touched.

QuestionA buffer has N = 6 slots. Currently the producer has put 4 items in and none have been removed. What are the values of e and f, and can the producer add another item?Show answer

f = 4 and e = 6 minus 4 = 2. The producer can add another item because e is 2, which is above 0, so it does not block. After that addition, e = 1 and f = 5.

QuestionWhy can the consumer be blocked even when the producer is fast?Show answer

Speed alone does not decide it. The consumer blocks whenever f = 0, meaning there is nothing in the buffer to take. A fast producer still has to write an item before the consumer can read it, so at the start, or after the consumer has drained everything, f is 0 and the consumer waits. That waiting is correct: it is the consumer waiting for work.

QuestionA stream arrives at 50 items per second and a consumer takes 30 per second. The buffer has 10 slots and starts empty. How long until the producer first blocks?Show answer

The net fill rate is 50 minus 30 = 20 items per second. The buffer holds 10 items, so it fills after 10 divided by 20 = 0.5 seconds. After that the producer blocks until the consumer removes items.

Sources