The idea
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
Thread T1 calls withdraw(5). Calling any monitor method first takes the monitor lock. The lock is free, so T1 takes it and walks in. While T1 holds it, T1 is the only thread active inside.
Thread T2 calls deposit(10) at the same moment. Its first move is to take the lock, but T1 holds it. So T2 waits outside in the entry queue. No two threads ever run inside together.
Inside, T1 tests its condition: is balance less than 5? The balance is 0, so T1 cannot go on. It must wait until another thread adds money.
Waiting inside
T1 calls funds.wait(). In one step it joins the funds queue, goes to sleep and releases the lock. If it slept holding the lock, T2 could never get in to deposit and both would be stuck.
The lock is free, so T2, first in the entry queue, takes it and walks in. It adds 10: the balance goes from 0 to 10. T1 is still asleep in the funds queue.
T2 calls funds.notify(), which wakes one thread from the funds queue. T1 wakes, but T2 still holds the lock and keeps running. So T1 joins the entry queue: it must win the lock again before it can go on.
T2 reaches the end of its with block. Leaving the method gives the lock back, and T2 walks out, its deposit done. T1, first in the entry queue, can now take the lock.
Holding the lock again, T1 returns from wait() to the top of its while loop and tests once more. Now the balance is 10, not less than 5, so the loop ends.
T1 takes 5: the balance goes from 10 to 5. Then it leaves the monitor and gives the lock back. Both calls are done, and no update was ever lost.
Mesa rules
Between notify() and T1 getting the lock, another thread could slip in first and take the money. A wake-up is only a hint, so a woken thread must test its condition again. That is why the test is a while loop.
Java builds monitors into the language: every object has a lock, and synchronized methods take it. Python and C have no monitor keyword, so you build the same object from a lock and a condition variable.
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.