AlgoViz
—
← Back to trail

Producer–Consumer

Medium+14 XP

Watch a fast producer and a slow consumer cooperate through a small shared buffer that fills and drains.

No visualization loaded.

Watch

—

i

Press Run to begin.

A very common pattern: one part makes things (the producer), another uses them (the consumer), and a small shared buffer sits between them. Press Run to watch the buffer fill and drain — and see why the producer sometimes has to wait.

▸Why have a buffer in the middle at all?

So the two sides don't have to move in lockstep. The producer can race ahead and stash items in the buffer; the consumer takes them whenever it's ready. The buffer absorbs the difference in their speeds — like a conveyor belt between a fast packer and a slow truck loader.

▸What happens when the buffer is full?

The producer must WAIT — there's no room to put another item. It pauses until the consumer removes something and frees a slot. Likewise, if the buffer is EMPTY, the consumer must wait until the producer adds something. Full → producer waits; empty → consumer waits.

▸Isn't this just a message queue?

Same idea! You met the bounded buffer in System Design as a message queue. Here it's at the OS/thread level — a producer thread and consumer thread sharing one buffer in memory. The pattern shows up everywhere once you can see it.

▸What keeps the two threads from corrupting the buffer?

Locks (and signals). Because the buffer is shared, adding and removing must be done one-at-a-time, or you'd get a race condition. So producer-consumer is built on top of the locks you just learned — it's those tools put to real use.

🧠Producer–Consumer: a maker and a user cooperate through a small shared buffer, so they can run at different speeds. When the buffer is full the producer waits; when empty the consumer waits. It's the bounded buffer, built on locks.
a filled buffer slotitem just addedproducer blocked (buffer full)