Producer-consumer
medium 50 minA bounded buffer between those who make work and those who do it.
Video lesson · Chapter 1 of 6
Make a prediction
Producer-consumer
0:59Reel
Theory
Read or listen first. About 2 min.
What it is
Producer-consumer is a concurrency pattern. Producers create items, consumers process them, and a shared buffer lies between them. Both sides run at their own speed.
The buffer is safe for many threads. A producer that finds it full waits until there is room. A consumer that finds it empty waits until there is an item. Nobody asks again and again: waiting threads sleep and are woken.
A buffer with a limit is called bounded. The limit is what slows producers down to the speed of the consumers. This effect is called backpressure.
Why it exists
Two parts of a program rarely have the same speed. Called directly, the fast part waits for the slow part each time. With a buffer it waits only when the buffer is full.
It removes a dependency. Producers do not know how many consumers there are, where they run, or whether they are busy. So each side can be changed, tested and scaled alone.
It evens out bursts. A hundred orders in one second become ten seconds of steady work for ten servers.
It puts one difficult thing, safe waiting, into one small class instead of everywhere.
A short history
1965
Edsger Dijkstra's text Cooperating Sequential Processes (EWD 123) contains a section called The Bounded Buffer and solves it with semaphores.
1974
Tony Hoare's paper on monitors, published in October, uses a bounded buffer as an example of waiting with conditions.
2004
Java 5 adds
java.util.concurrentwith theBlockingQueueinterface. Its documentation says it is designed mainly for producer-consumer queues.2011
The technical paper on the LMAX Disruptor, dated May 2011, describes a ring that is allocated once and is used in place of queues between threads.
2024
Python 3.13 adds
shutdowntoqueue.Queue: a closing call like the one built on this page.
Words to know
- Producer
- Code that creates items and puts them into the buffer.
- Consumer
- Code that takes items out and processes them.
- Bounded buffer
- A queue with a capacity.
putmay wait. - Backpressure
- A slow consumer slows the producer down, through the full buffer.
- Condition
- A waiting room that belongs to a lock. Threads sleep there until signalled.
- Busy waiting
- Asking again and again in a loop. Costs processor time and does no work.
- Drain
- Accept nothing new and process what is left.
- Poison pill
- A special item that tells a consumer to stop.
- MPMC, SPSC
- Many producers and many consumers; single producer and single consumer.
- Lease
- An item that is lent for a limited time and returns if no acknowledgement arrives.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Produce. Create an item, call put.
Understand it
Story
A rack between the saw and the stove
Two people share work. One makes things, the other uses them, and they are never equally fast. If they hand over directly, one of them is always standing around. A small shelf between them changes that, and it brings two new questions: what if the shelf is full, and what if it is empty?
The rack is the buffer, its four places the capacity, the two bells the two conditions, the lantern the close.
Four participants
Producer
Creates items and calls
put. A request handler, a file reader, a sensor, a chef.Buffer
Holds items safely between threads. A blocking queue, a channel, a ring.
Consumer
Calls
takeand processes. A worker, a log writer, a waiter with two plates.Coordination
A lock for the items, and a way to wait for room and for items. It lives inside the buffer.
The problem
What goes wrong without it
Take a pizza kitchen. The first version lets each chef call a server directly. The chef then stands with the pizza in hand until somebody is back from the tables. The second version shares a plain list, and it looks fine for weeks:
counter = []def chef(): while True: counter.append(bake()) # 1. grows for ever on a busy eveningdef server(): while True: if counter: # 2. two servers may both see the last pizza deliver(counter.pop(0)) # and the second pop raises IndexError # 3. nothing to do? ask again, a million times a second| Fault | Name | What the buffer does about it |
|---|---|---|
| Check and pop are two steps | Race | One lock around both |
| The loop spins while it is empty | Busy waiting | Sleep until signalled |
| The list has no limit | Unbounded growth | A capacity, and a decision for the full case |
| A chef and a server are coupled | Same speed for both | They only know the buffer |
sleep(0.1) to the loop hides the third fault and adds up to 100 ms of delay to each pizza.The design that hurts
1/3The chef knows the servers
To hand over a pizza the chef looks for a free server. Hire one more, and every chef must be told.
uses
The idea
One object that can make you wait
The buffer is an ordinary class with two unusual methods. put returns when the item is inside. take returns when there is an item. If that is not possible now, the calling thread sleeps inside the method. Callers write straight code, and all coordination sits in one place.
Producer-consumer in general
1/5The buffer
A queue, a capacity, and a flag for the end. Nothing in it is public except the methods.
implementsusesowns (dies together)
A full counter, and a pizza that waits
Five scenes to know
| Scene | What happens | Who is woken |
|---|---|---|
| put, room left | Lock, add, unlock | One consumer |
| take, items left | Lock, remove the oldest, unlock | One producer |
| put, full | Sleep on notFull, then check again | Later, by a take |
| take, empty | Sleep on notEmpty, then check again | Later, by a put |
| Several of each | The lock lets one thread at a time change the items | Whoever waits for what just became true |
The promise of the buffer
Waiting
Two waiting rooms, and a second look
How a condition releases the lock, why threads can wake without a signal, and how to build one from scratch belong to Monitor and Coordination. For this pattern three rules are enough.
- 1
Ask in a loop
while full: wait(), neverif. Between the signal and your turn another thread may have used the free place. - 2
Signal the other side, once
One item added helps exactly one consumer. One item removed helps exactly one producer.
signalis enough when the two sides wait in two rooms. - 3
Share one room? Then wake all
Java's
waitandnotifyon one object have a single room.notifycan wake the wrong side, which goes back to sleep, and the right side is never told.
from collections import dequedef play(notify_all): """One waiting room for everybody. Capacity 1, two producers and two consumers, one unlucky order.""" items, room = 0, deque() def wake(): woken = list(room) if notify_all else [room[0]] if room else [] for w in woken: room.remove(w) return deque(woken) def step(who): nonlocal items if who[0] == "P" and items == 0: items = 1 return wake() if who[0] == "C" and items == 1: items = 0 return wake() room.append(who) # the condition is false: (back) to the waiting room return deque() ready = deque(["C1", "C2", "P1", "P2"]) while ready: ready.extend(step(ready.popleft())) return items, list(room)print("notify one:", play(False)) # (0, ['P2', 'C2']): empty, and a producer asleepprint("notify all:", play(True)) # (0, []): everyone finishedInside put
take is the mirror image, with one difference: closed is only the end if it is also empty.Capacity
Why the limit is the best part
A buffer absorbs bursts. It can not repair a lasting difference in speed. If 120 items arrive each second and 100 are processed, an unlimited buffer grows by 20 each second: 72,000 after an hour, and each new item waits 12 minutes. The limit turns this slow disaster into an early, visible answer: the producer has to wait.
The consumers can not keep up on Friday evening. What does the buffer do?
BreaksUnbounded queue
- How
- Accept everything, memory is cheap.
- Limit
- Waiting time grows without end. Finally the process dies and all waiting items are lost together.
- Choose when
- Only if the number of items is limited elsewhere, for example one per connected user.
WorksHuge bounded queue
- How
- Capacity one million, to be safe.
- Limit
- No crash, but items wait for hours before anyone notices. The limit is a number nobody chose.
- Choose when
- Offline jobs, where only throughput counts.
StrongSmall bound, chosen from the wait you accept
- How
- Capacity = items per second x seconds of waiting you allow. Decide what a full buffer means: wait, refuse, or drop. Count it.
- Limit
- Producers must be able to handle waiting or refusal.
- Choose when
- Anything that serves people.
The life of a buffer
Judgement
When to use it and when not
Fits
- Two sides with different or changing speed
- Work may be done later, in another thread
- Bursts that should be evened out
- Several workers should share one stream of work
- A slow resource such as a disk behind a fast caller
Does not fit
- The caller needs the result now: use a future
- Everyone must see every item: that is publish-subscribe
- The work takes less time than the hand-over
- One thread is fast enough
- Items must survive a crash: use a message broker
Which hand-over?
Relatives
| Page | Relation |
|---|---|
| Thread pool | Producer-consumer where the items are tasks and the consumers are managed for you |
| Semaphore | Two counters, free places and filled places, can replace the two conditions |
| Job scheduler | A buffer ordered by time instead of arrival |
| Logger | A famous consumer: one thread that owns the file |
| Message queues | The same shape between machines, with storage |
The price
Delay
Every item waits at least a little. Full buffers wait longest.
Lost at a crash
Items in memory are gone with the process.
Errors move away
The producer has returned long ago when the item fails.
The end is hard
Stopping without losing or hanging needs a plan.
Summary
The whole topic in one minute.
A bounded buffer stands between producers and consumers. It owns one lock and two conditions. put waits while full, take waits while empty, each in a loop, and each wakes one thread of the other side.
The capacity is a decision about waiting time: rate times seconds. What a full buffer means, waiting, refusing or dropping, is a decision too, and it is counted.
The end is part of the design: producers stop, the buffer closes, consumers drain and leave. In production add leases for items in work, lanes for order, and batches for speed.
- Two sides, one buffer, and no arrow between the sides.
- Full means producers wait, empty means consumers wait.
- One lock, two conditions, and a loop around each wait.
- The bound gives backpressure. It is a decision in seconds, not a guess in items.
- Close, drain, join: plan the end before the start.