Producer–Consumer
Medium+14 XPWatch a fast producer and a slow consumer cooperate through a small shared buffer that fills and drains.
No visualization loaded.
Watch
—
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.