← 🔒 Synchronization & Concurrency
Subtopic 5 of 5

3.5Monitors, condition variables and priority inversion

The idea

A monitor bundles shared data with the procedures that use it and lets only one process be active inside at a time. Condition variables let a process wait inside it.

Think of it like this: A shop with one customer allowed in the till area at a time, and a waiting bench you step onto when the item you want is out of stock.

Why it exists

It is much harder to misuse than raw semaphores, because the compiler enforces mutual exclusion.

How it works

  1. Enter the monitor (automatic mutual exclusion).
  2. If the condition is false: wait() releases the monitor and sleeps.
  3. Another process calls signal() to wake one waiter.
  4. A signal with no waiter is lost, unlike a semaphore V.

Worked example: Semaphore V versus condition signal

V on a semaphore nobody waits on raises the count: the signal is remembered. signal() on a condition with no waiters does nothing: it is forgotten.

Now play with it

  • →Use the semaphore lab "order" scenario: V before P still works because the count is remembered.
  • →Read the comparison table and say which tools sleep and which spin.
T1
S1
V(s)
T2
P(s) (blocked)
S2
semaphore s0
Threads in critical section0
Statusrunning
No steps yet.

A semaphore initialised to 0 makes T2 wait until T1 has executed S1. P(s) waits until s > 0 then decrements; V(s) increments.

ToolOwner / memoryWaitingTypical use
Spinlockany threadbusy waitsvery short sections on multiprocessors
Mutexmust be unlocked by the thread that locked itsleepsgeneral mutual exclusion
Semaphoreno owner; the count is rememberedsleepscounting resources, ordering
Monitor + condition variableone active process inside; signal with no waiter is lostsleepslanguage-level synchronization

Check yourself

A spinlock is most appropriate when

Remember: Monitor: one active process, signal can be lost. Semaphore: count remembered. Spinlock: only for very short waits on multiprocessors.
Exam notes (the dense version)

A monitor is a language-level construct: shared data plus procedures, with only one process active inside at a time. Condition variables support wait() (release the monitor and sleep) and signal() (wake one waiter). Unlike a semaphore, a signal with nobody waiting is lost. Other tools: mutex (owned by the locker), spinlock (busy-wait, good only for very short waits on multiprocessors), barrier. Priority inversion and its fix, priority inheritance, belong here too.

Previous year questions: Synchronization & Concurrency (10)

PYQs are grouped by topic, so this is the full set for Synchronization & Concurrency; try the ones that match this subtopic. Open all 10 on the topic page.