Monitors
About this lesson
Locks and condition variables work, but they are easy to misuse: forget one unlock and every thread is stuck. A monitor packs the shared data, its lock and its condition variables into one object, and only the object's methods may touch the data. Follow two threads through a tiny bank account monitor: one wants to withdraw 5 from an empty account and must wait, the other deposits 10 and wakes it. You will see the two queues every monitor has, and why a woken thread must check its condition again. The Software lesson Threads and concurrency shows the race these tools prevent, and the Condition variables lesson in this module explains wait and signal on their own.
Data, lock and queue in one
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.
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
Read the lesson step by step
Data, lock and queue in one
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.
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 guardT1 enters and takes the lock
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.
T1 withdraw(5) line 2 with lock: take the monitor lock lock free -> T1 inside T1 entry queue (empty)One thread at a time
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.
T2 deposit(10) line 7 with lock: lock is held by T1 T2 sleeps in the entry queue lock T1 entry queue T2 mutual exclusion: at most one thread insideT1 checks the balance
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.
line 3 while balance < n: 0 < 5 true: not enough money T1 holds the lock, so the balance cannot change while it looks: the test is safeWaiting gives the lock back
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.
line 4 funds.wait() atomically: T1 joins the funds queue T1 sleeps the lock is released lock T1 -> free funds queue T1T2 gets in and deposits
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.
lock free -> T2 line 8 balance += n balance 0 -> 10 funds queue T1 (asleep)notify() wakes T1, T2 stays
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.
line 9 funds.notify() funds queue T1 -> (empty) entry queue T1 (woken, needs the lock again) lock still T2: notify() does not release it this is Mesa semantics: signal and continueT2 leaves, the lock passes 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.
line 7 end of the with block: release the lock T2 done lock T2 -> free (T1 is next in line) entry queue (empty)T1 checks again
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.
lock free -> T1 wait() returns with the lock held by T1 line 3 while balance < n: 10 < 5 false: leave the loopT1 withdraws and leaves
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.
line 5 balance -= n balance 10 -> 5 lock T1 -> free both threads done; queues emptyWhy while, not if
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.
Hoare (1974) signal hands the lock straight to the woken thread: the condition still holds Mesa (1980) signal only makes it runnable; the signaller keeps the lock (this lesson) nearly every real system uses Mesa semantics, and wait() may also wake for no reason (spurious wake-up) -> always: while not condition: wait()Monitors in real code
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.
the same monitor in C99 with POSIX threads: #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> static int balance = 0; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t funds = PTHREAD_COND_INITIALIZER; static void withdraw(int n) { pthread_mutex_lock(&lock); /* enter */ while (balance < n) pthread_cond_wait(&funds, &lock); balance -= n; pthread_mutex_unlock(&lock); /* leave */ } static void deposit(int n) { pthread_mutex_lock(&lock); balance += n; pthread_cond_signal(&funds); pthread_mutex_unlock(&lock); } static void *t1(void *arg) { (void)arg; withdraw(5); return NULL; } static void *t2(void *arg) { (void)arg; deposit(10); return NULL; } int main(void) { pthread_t a, b; pthread_create(&a, NULL, t1, NULL); pthread_create(&b, NULL, t2, NULL); pthread_join(a, NULL); pthread_join(b, NULL); printf("balance %d\n", balance); return 0; } prints: balance 5 and as a Python program: import threading balance = 0 lock = threading.Lock() funds = threading.Condition(lock) # a condition tied to the lock waiting = threading.Event() def withdraw(n): global balance with lock: # enter: take the monitor lock while balance < n: print("T1 waits: balance", balance) waiting.set() funds.wait() # release lock, sleep, re-take lock balance -= n print("T1 took", n, "-> balance", balance) def deposit(n): global balance with lock: balance += n print("T2 put", n, "-> balance", balance) funds.notify() # wake one waiter; T2 keeps the lock t1 = threading.Thread(target=withdraw, args=(5,)) t1.start() waiting.wait() # start T2 once T1 is waiting t2 = threading.Thread(target=deposit, args=(10,)) t2.start() t1.join(); t2.join() print("balance", balance) prints: T1 waits: balance 0 T2 put 10 -> balance 10 T1 took 5 -> balance 5 balance 5
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What does a monitor guarantee about the threads that call its methods?
Calling a monitor method first takes the monitor lock, so only the lock holder runs inside. Others wait in the entry queue until the lock is given back.
02T1 is inside the monitor, finds balance 0 and calls funds.wait(). What happens to the monitor lock?
wait() joins the condition's queue, sleeps and releases the lock atomically. If T1 slept holding the lock, no depositor could ever get in, and both threads would wait forever.
03Under Mesa semantics (used by Python, POSIX threads and Java), what does notify() do?
Mesa semantics are signal and continue: the woken thread becomes runnable and must win the lock again. Hoare's original semantics handed the lock straight over instead.
04Why does withdraw test 'while balance < n' instead of 'if balance < n' before waiting?
Between notify() and the woken thread getting the lock, another thread can slip in and change the data, and waits can also end spuriously. Re-testing in a loop is always correct.
05In the worked example the account starts at 0, T2 deposits 10 and T1 withdraws 5. What is the balance at the end?
T1 waits until the deposit makes the balance 10, then takes 5, leaving 5. Because both updates run while holding the lock, neither is lost, whichever thread runs first.
Glossary
- Monitor
- An object that bundles shared data with one lock and zero or more condition variables. Only its methods touch the data, and only one thread runs inside at a time.
- Monitor lock
- The lock a monitor takes automatically when a thread calls one of its methods, and gives back when the method returns or the thread waits.
- Entry queue
- The threads waiting outside a monitor for its lock, so they can enter.
- Condition variable
- A queue of threads waiting inside a monitor for some state to change, such as enough money. wait() joins it; notify() or signal() wakes a waiter.
- Mesa semantics
- Signal and continue: notify() only makes a waiter runnable, and the notifier keeps the lock. Named after the Mesa language from Xerox PARC; used by almost every real system.
- Hoare semantics
- Signal and wait: signal() hands the lock straight to the woken thread, which runs at once. Named after Tony Hoare, who described monitors in 1974.
- Spurious wake-up
- A wait() that returns although no thread signalled. POSIX allows it, which is one more reason to test the condition in a loop.
Notes and sources
- Per Brinch Hansen described monitors in his 1973 book Operating System Principles, and C.A.R. Hoare refined them in "Monitors: An Operating System Structuring Concept" (CACM, October 1974). Lampson and Redell's Mesa paper (CACM, February 1980) changed signal into a hint, the meaning used almost everywhere today.
- The card shows the two methods with the monitor's fields written as plain names (balance, lock, funds). The full Python program in the last step keeps them as globals and uses threading.Lock and threading.Condition; the C version uses a pthread mutex and condition variable.
- 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.
- 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.
- In Java every object can act as a monitor: synchronized methods take the object's lock, and wait(), notify() and notifyAll() use the object's single built-in condition queue.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, appendix D: Monitors
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 30: Condition Variables
- Berkeley CS162, Lecture 9: Semaphores, Monitors and Readers/Writers
- MIT 6.1810 (2024), lecture notes: Coordination (sleep and wakeup)
- Python documentation: threading, Condition objects
- POSIX man page: pthread_cond_wait(3p)
- POSIX man page: pthread_cond_broadcast(3p) and pthread_cond_signal
- Linux kernel documentation: Completions (wait queues in the kernel)
Quiz Unlocks after the last step.