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
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
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
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
criticalAfter waking, another thread may have been quicker.
Wrongif len(self._items) == self._capacity: self._not_full.wait()self._items.append(item)Rightwhile len(self._items) == self._capacity: self._not_full.wait()self._items.append(item)Work inside the lock
criticalWhile one server walks to the table, nobody can touch the counter.
Wrongwith self._lock: pizza = self._items.popleft() deliver(pizza)Rightpizza = self._buffer.take()deliver(pizza)No capacity
majormaxsize 0 means unlimited. The queue hides the problem until memory ends.
Wrongjobs = queue.Queue()Rightjobs = queue.Queue(maxsize=100) # 200/s x 0.5 sA stop flag
majorA sleeping consumer never reads it, and items stay behind.
Wrongwhile self.running: item = buffer.take()Righttry: while True: work(buffer.take())except Closed: passAsking before taking
majorBetween the question and the take another consumer gets the item.
Wrongif not q.empty(): item = q.get() # may wait for everRighttry: item = q.get(timeout=1)except queue.Empty: ...Closing too early
criticalChefs are still baking. Their pizzas are refused.
Wrongbuffer.close()for t in chefs: t.join()Rightfor 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.