AlgoViz

Monitor

medium 50 min

A 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

0:00 / 4:27

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

LeeThreadisinsideMaxThreadisawayNoorThreadisawayroomPaintRoomlitres2insideLeemore_paintConditionasleepnonemore_roomConditionasleepnonedraw(5)

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

AWorkerisworksBWorkerisasleepmainThreaddeskJobDeskjobs0closednoasleepB

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

    critical

    The state may have changed before the thread got the lock.

    Wrong
    if not items:    cond.wait()return items.pop()
    Right
    while not items:    cond.wait()return items.pop()
  • Sleeping with the lock

    critical

    Nobody can enter and bring what you wait for.

    Wrong
    with lock:    while not items:        time.sleep(0.1)
    Right
    with cond:    while not items:        cond.wait()
  • Forgetting to signal

    critical

    A new method changes the state and the sleepers never hear of it.

    Wrong
    def clear(self):    with self.lock:        self.items.clear()
    Right
    def clear(self):    with self.lock:        self.items.clear()        self.not_full.notify_all()
  • notify with mixed waiters

    critical

    The wrong kind wakes and the right one sleeps.

    Wrong
    # takers and putters on one conditioncond.notify()
    Right
    cond.notify_all()      # or two conditions
  • Giving the list away

    major

    The caller changes it without the lock.

    Wrong
    def all(self):    with self.lock:        return self.items
    Right
    def all(self):    with self.lock:        return list(self.items)
  • Calling listeners inside

    major

    They may be slow, or call back.

    Wrong
    with lock:    for l in listeners:        l(value)
    Right
    with 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.