Skip to the guide

Producer–consumer and blocking queues

IntermediateConcept7 pages

In the producer–consumer pattern, some threads make work and others do it, with a queue between them. A blocking queue is a queue that makes a thread wait when it is full or empty. The interviewer wants you to build one correctly, and to say what happens when the two sides run at different speeds.

Two people washing up

Two friends are washing up after a big dinner. One washes and stands each plate on a drying rack with four places, and the other takes plates off the rack and dries them. Washing is faster, so sometimes the rack is full, and the washer must stop until a place opens. Sometimes the rack is empty, and the drier must wait. Whoever changes the rack calls out, so anyone waiting looks up.

Now imagine two people drying, both resting because the rack is empty. A plate lands, the washer calls out, and both get up. One takes the plate. The other must look at the rack again before reaching. If she doesn't look, she reaches into empty air and decides the washing-up is finished, and she goes home with plates still to come. At the end of the night, the washer says "that's the last one", and the driers finish what is left and stop.