Monitors
Entry queue, condition queues and signalling — animated.
Operating Systems: Monitors
1. What is a Monitor?
A Monitor is a high-level synchronization construct that encapsulates shared data variables, local structures, and the procedures that operate on them. Unlike lower-level constructs (such as mutexes or semaphores), a monitor guarantees automatic mutual exclusion—only one process can be active inside the monitor at any given time.
Implicitly handled by the compiler/runtime system. Developers do not need to manually call entry or exit lock procedures.
Provide explicit synchronization primitives allowing processes to block and wait when specific conditions are not met.
Combines data hiding and thread safety into an object-oriented encapsulation model, drastically reducing synchronization bugs.
The syntax prevents common errors like forgetting to release a lock or bypassing critical section entry rules.
2. BoundedBuffer Monitor Structure
Below is the standard C/Java-style pseudocode implementation for a bounded buffer using condition variables:
monitor BoundedBuffer { int buffer[N]; int count = 0; int in = 0, out = 0; condition full, empty; procedure insert(item) { if (count == N) wait(full); buffer[in] = item; in = (in + 1) % N; count++; signal(empty); } procedure remove() { if (count == 0) wait(empty); item = buffer[out]; out = (out + 1) % N; count--; signal(full); return item; } }
Understanding Condition Variables:
Condition variables do not hold values or act as counters. They are purely waiting queues for process signaling:
wait(c): Suspends execution of the calling process until another process callssignal(c). The process releases its exclusive monitor lock while waiting.signal(c): Resumes exactly one suspended process waiting on conditionc. If no processes are waiting, the signal has no effect (unlike semaphores).broadcast(c): Resumes all suspended processes currently queued on conditionc.
3. Interactive BoundedBuffer Monitor Simulator
Simulate producers calling insert() and consumers calling remove() on a monitor with buffer capacity \(N = 4\).
• full.wait_queue: []
• empty.wait_queue: []