AlgoViz

Producer-consumer

medium 50 min

A bounded buffer between those who make work and those who do it.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:26

See it run

Threads as objects: who sleeps, who is woken, and what the buffer holds at each moment.

Operations

Pizza kitchen

Mario bakes, Asha delivers, the counter holds five. M, P, H, V, B and L are pizzas.

Step 1 of 9

Opening time

MarioChefstateidleAshaServerstateasleepcounterBoundedBufferitemsnonesize0 of 5take()

The counter is empty. Asha calls take and sleeps on notEmpty.

Step 1: Opening time

def put(self, item):    with self._lock:        while full and not closed:            self._not_full.wait()        if closed: raise Closed        self._items.append(item)        self._not_empty.notify()def take(self):    with self._lock:        while empty and not closed:            self._not_empty.wait()        if empty: raise Closed        item = self._items.popleft()        self._not_full.notify()        return item
Watch
The state of each person
Result
The counter slows Mario

Ask at each step: who is asleep, and who will wake them?

In the real world

The same producer-consumer doing real jobs. Pick one and step through it.

Two programs print at once. One queue, one printer.

Step 1 of 4

Print and go on

writerProgramprintsletterdesignerProgramspoolerQueuejobsletterprinterConsumerprintsnothingput(letter)

The writer hands in a letter. The program is free at once.

Step 1: Print and go on

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • if around the wait

    critical

    After waking, another thread may have been quicker.

    Wrong
    if len(self._items) == self._capacity:    self._not_full.wait()self._items.append(item)
    Right
    while len(self._items) == self._capacity:    self._not_full.wait()self._items.append(item)
  • Work inside the lock

    critical

    While one server walks to the table, nobody can touch the counter.

    Wrong
    with self._lock:    pizza = self._items.popleft()    deliver(pizza)
    Right
    pizza = self._buffer.take()deliver(pizza)
  • No capacity

    major

    maxsize 0 means unlimited. The queue hides the problem until memory ends.

    Wrong
    jobs = queue.Queue()
    Right
    jobs = queue.Queue(maxsize=100)   # 200/s x 0.5 s
  • A stop flag

    major

    A sleeping consumer never reads it, and items stay behind.

    Wrong
    while self.running:    item = buffer.take()
    Right
    try:    while True: work(buffer.take())except Closed: pass
  • Asking before taking

    major

    Between the question and the take another consumer gets the item.

    Wrong
    if not q.empty():    item = q.get()          # may wait for ever
    Right
    try: item = q.get(timeout=1)except queue.Empty: ...
  • Closing too early

    critical

    Chefs are still baking. Their pizzas are refused.

    Wrong
    buffer.close()for t in chefs: t.join()
    Right
    for t in chefs: t.join()buffer.close()

Interview tips

  • Start with the sleepers

    • Who waits?
    • For what?
    • Who wakes them, also at the end?
  • Say the bound

    • Rate times seconds.
    • What does full mean?
    • Count refusals and drops.
  • Keep it generic

    • No pizza in the buffer.
    • No thread in the chef.
    • No lock outside.
  • Plan the end

    • Join makers.
    • Close.
    • Drain, join takers.
  • In production

    • Age of the oldest item.
    • Number of living consumers.
    • Parked items.