Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 66 ยท Synchronization

Monitors and Condition Variables

Learn how a monitor bundles data, a lock and condition variables, why you wait in a while loop, and build a bounded buffer and philosophers with a Python simulation.

Semaphores work, but the programmer must place every wait and signal by hand. One forgotten call corrupts the program, and nothing in the language helps you find it. A monitor is a higher-level construct that moves the bookkeeping into the language or library: shared data, the procedures that use it, and the lock that protects it are packaged together.

A monitor has three ingredients:

  1. Shared data that is private to the monitor.
  2. Operations that access that data. Only one thread at a time can be active inside the monitor: entering acquires an implicit lock, leaving releases it. You never write wait(mutex) yourself.
  3. Condition variables for waiting inside the monitor until something becomes true.

Condition variables: wait and signal

A condition variable cv represents a queue of threads waiting for some condition ("buffer not empty", "my chopsticks are free"). It supports:

  • cv.wait(): release the monitor lock and sleep on the queue, atomically. When woken, reacquire the lock before continuing.
  • cv.signal() (or notify): wake one waiting thread, if any. Nothing happens if nobody waits (a signal is not remembered, unlike a semaphore's count).
  • cv.broadcast() (or notify_all): wake all waiting threads.
sequenceDiagram
    participant A as Thread A (consumer)
    participant M as Monitor lock
    participant B as Thread B (producer)
    A->>M: enter (lock)
    A->>A: buffer empty, so wait()
    A-->>M: lock released, A sleeps on cv
    B->>M: enter (lock)
    B->>B: add item
    B->>A: signal()
    B-->>M: leave (unlock)
    A->>M: wakes up, reacquires lock
    A->>A: recheck condition, take item

Waiting always releases the lock, otherwise nobody could ever make the condition true.

Why the condition is checked in a loop

There are two styles of signalling. In Hoare monitors the signaller hands the lock directly to the woken thread, so the condition is guaranteed true on return. Almost every real system (Java, pthreads, Python, Go's sync.Cond) uses Mesa semantics: the woken thread merely becomes runnable and competes for the lock. Before it runs, another thread may have taken the item. So you must always write:

TEXT
while not condition:      # NOT "if"
    cv.wait()

Spurious wake-ups are allowed too. The loop makes both cases harmless.

A monitor in the simulation

Our mini kernel now understands five requests: lock, unlock, wait (release the lock and sleep on a condition), signal and broadcast. A signalled thread goes back to contending for the lock, which is the Mesa rule.

Python A bounded buffer as a monitor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The producers and consumers contain no semaphore arithmetic at all: only "wait until the condition holds" and "tell others the state changed". All ten items arrive and nobody is stuck. Compare this with the three-semaphore solution.

Dining philosophers with a monitor

The monitor solution to the dining philosophers avoids chopstick semaphores. Each philosopher has a state (THINKING, HUNGRY, EATING) and a condition variable. A philosopher may start eating only if neither neighbour is eating, and a philosopher who finishes checks whether either neighbour can now eat.

TEXT
pickup(i):  state[i] = HUNGRY
            test(i)
            while state[i] != EATING: wait(self[i])
putdown(i): state[i] = THINKING
            test(left(i)); test(right(i))
test(i):    if state[i] == HUNGRY and neighbours not eating:
                state[i] = EATING; signal(self[i])

Because a philosopher takes both chopsticks as one decision, a circular wait is impossible.

Python Philosophers in a monitor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each philosopher finishes four meals and no two neighbours ever eat at the same time. This version prevents deadlock; a philosopher can still be bypassed repeatedly in unlucky schedules, so strict fairness needs extra ordering.

Monitors in real languages

You use monitors every day without the name. In Java every object has a built-in monitor: synchronized enters it, wait(), notify() and notifyAll() are the condition operations. Python's threading.Condition, C's pthread_cond_t with a mutex, and C++'s std::condition_variable offer the same pieces as library calls:

Python
import threading

cv = threading.Condition()
items = []

def consumer():
    with cv:                       # enter the monitor
        while not items:           # loop, not if
            cv.wait()              # release lock + sleep
        print(items.pop(0))

def producer(x):
    with cv:
        items.append(x)
        cv.notify()                # wake one waiter

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cv.wait() do with the monitor lock?

    Releasing the lock lets other threads enter and change the state; the woken thread must reacquire the lock before continuing.
  2. 2. Why should you wait in a while loop rather than an if statement?

    With Mesa semantics, another thread can run between the signal and the wake-up and invalidate the condition, and spurious wake-ups are allowed.
  3. 3. What happens when signal is called but no thread is waiting?

    Unlike a semaphore, a condition variable has no memory, so the condition itself (checked in the loop) must be the source of truth.
  4. 4. Which of these is a monitor in Java?

    Every Java object carries a monitor: synchronized acquires it and wait, notify and notifyAll operate on its condition queue.

Summary

  • A monitor packages shared data, a built-in lock and condition variables; only one thread is active inside at a time.
  • wait atomically releases the lock and sleeps; signal or broadcast wakes waiters, who must reacquire the lock.
  • Always test the condition in a while loop (Mesa semantics).
  • Signals are not remembered, unlike semaphore counts.
  • Java synchronized, pthread_cond_t, std::condition_variable and threading.Condition are everyday monitors.

Next: Priority Inversion, Starvation and Livelock