Coordination: waiting and handing over
hard 50 minCoordination makes one thread go on only after another has done something.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Threads that wait for a fact, for work, for each other and for a thing.
Operations
Hand over pages
One place, two threads, and a clean end.
Step 1 of 9
The printer is early
The shelf is empty. The printer sleeps on arrived and costs nothing.
Step 1: The printer is early
def put(self, item): with self._lock: while self._full and not self._closed: self._space.wait() if self._closed: raise Closed() self._item, self._full = item, True self._arrived.notify()def take(self): with self._lock: while not self._full and not self._closed: self._arrived.wait() if not self._full: raise Closed() item, self._full = self._item, False self._space.notify() return itemdef close(self): with self._lock: self._closed = True self._arrived.notify_all() self._space.notify_all()- Watch
- full and closed
- Result
- No page lost
Each wait asks for its fact or for closed.
In the real world
The same coordination doing real jobs. Pick one and step through it.
Three parties, one never comes. The round breaks for all.
Step 1 of 3
Two of three
A and B sleep in round 1.
Step 1: Two of three
Common mistakes
The bugs interviewers watch for, with the fix beside each.
if around wait
criticalThe fact may be false again when the thread runs.
Wrongif not self._full: self._arrived.wait()Rightwhile not self._full: self._arrived.wait()Notify before the state
criticalThe waiter wakes, sees nothing, sleeps, and no second signal comes.
Wrongself._arrived.notify()self._full = TrueRightself._full = Trueself._arrived.notify()Close that wakes one
criticalThe other takers sleep forever.
Wrongself._closed = Trueself._arrived.notify()Rightself._closed = Trueself._arrived.notify_all()self._space.notify_all()Counting inside the thread
majorJoin may see zero before the thread has begun.
Wrongdef _run(self, job): self._running += 1 job()Rightself._running += 1 # in start, under the lockthreading.Thread(target=self._run).start()Count down only on success
majorOne failed check and the start never happens.
Wrongcheck()latch.count_down()Righttry: check()finally: latch.count_down()A sleep that cannot hear
majorShutdown takes as long as the longest sleep.
Wrongtime.sleep(3600)Rightif stop.pause(3600): return
Interview tips
Name the fact
- Which field?
- Which lock?
- Who makes it true?
Wait well
- In a loop.
- Fact before clock.
- With a deadline.
Tell well
- State first.
- One, if any will do.
- All, on close.
End well
- Finally counts down.
- First error wins.
- Nobody runs after join.