Monitor
medium 50 minA monitor puts shared data, the lock that guards it and the conditions threads wait for into one object.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who is inside, who sleeps on which condition, and what the state says.
Operations
Paint room
Lee needs 5 of 2 litres. The story as objects.
Step 1 of 8
Lee enters
The lock is free. 2 litres are there, 5 are needed.
Step 1: Lee enters
def draw(self, n): with self.lock: while self.litres < n: self.more_paint.wait() self.litres -= n self.more_room.notify_all()def pour(self, n): with self.lock: while self.litres + n > 10: self.more_room.wait() self.litres += n self.more_paint.notify_all()- Watch
- inside and asleep
- Result
- Woken is not inside
A woken thread goes past the door and looks again.
In the real world
The same monitor doing real jobs. Pick one and step through it.
One worker works, one sleeps, and the desk closes.
Step 1 of 4
Two workers
A has a job, B sleeps.
Step 1: Two workers
def take(self): with self.lock: while not self.jobs and not self.closed: self.changed.wait() if not self.jobs: raise Closed() return self.jobs.popleft()def close(self): with self.lock: self.closed = True self.changed.notify_all()Common mistakes
The bugs interviewers watch for, with the fix beside each.
if around wait
criticalThe state may have changed before the thread got the lock.
Wrongif not items: cond.wait()return items.pop()Rightwhile not items: cond.wait()return items.pop()Sleeping with the lock
criticalNobody can enter and bring what you wait for.
Wrongwith lock: while not items: time.sleep(0.1)Rightwith cond: while not items: cond.wait()Forgetting to signal
criticalA new method changes the state and the sleepers never hear of it.
Wrongdef clear(self): with self.lock: self.items.clear()Rightdef clear(self): with self.lock: self.items.clear() self.not_full.notify_all()notify with mixed waiters
criticalThe wrong kind wakes and the right one sleeps.
Wrong# takers and putters on one conditioncond.notify()Rightcond.notify_all() # or two conditionsGiving the list away
majorThe caller changes it without the lock.
Wrongdef all(self): with self.lock: return self.itemsRightdef all(self): with self.lock: return list(self.items)Calling listeners inside
majorThey may be slow, or call back.
Wrongwith lock: for l in listeners: l(value)Rightwith lock: tell = list(listeners)for l in tell: l(value)
Interview tips
Three lists first
- What is always true.
- What a thread waits for.
- What makes it true.
Every method
- Enter.
- While not, wait.
- Change, signal, leave.
Signals
- A hint, not a promise.
- One condition per reason.
- In doubt, all.
Never inside
- Network or disk.
- Sleep.
- Foreign code.
In production
- Closed in each condition.
- Deadlines, not durations.
- Visits times time inside.