MONITOR1def withdraw(n):2 with lock:3 while balance < n:4 funds.wait()5 balance -= n6def deposit(n):7 with lock:8 balance += n9 funds.notify()balance0fundsMONITORMONITORlockfreeT1T2
Right: the monitor (balance, funds queue, the lock at its one door)Left: its methods; front: the entry queue, waiting for the lockTokens: threads T1 and T2, and the notify() envelopeThe monitor's two methods on the left. On the right the monitor itself: the balance and the funds queue inside, one doorway with the lock box beside it, and the entry queue in front. T1 enters holding the lock and finds balance 0, so it sleeps in the funds queue and the lock frees. T2, waiting outside, enters, deposits 10 and notifies; T1 rejoins the entry queue, re-enters after T2 leaves, checks again and withdraws 5. The two queues come from Lampson and Redell: a monitor lock queue (the entry queue here) and one queue per condition variable. Inside the Linux kernel, sleeping threads wait on wait queues in the same way.

The idea

  1. A monitor bundles shared data, here a bank balance, with one lock and a condition variable. Threads may only reach the data by calling the monitor's methods, and the monitor takes and gives back the lock for them.

One at a time

Waiting inside

Mesa rules

What happens

;; step 1/12 · idea
monitor Account
  data        balance = 0
  lock        one, taken on entry, given back on exit
  condition   funds: a queue of threads waiting for money
  methods     withdraw(n), deposit(n): the only way in

Brinch Hansen (1973), Hoare (1974): a lock and zero or
more condition variables, packed with the data they guard

The two queues come from Lampson and Redell: a monitor lock queue (the entry queue here) and one queue per condition variable. Inside the Linux kernel, sleeping threads wait on wait queues in the same way. The figure follows one possible order: T1 runs first and must wait. The Python program forces that order with an Event so its output is always the same; the C program leaves the order to the scheduler, and either way it prints balance 5.