Intermediate Topic 22 of 51 Operating Systems
Monitors
Language-level constructs bundling data, locks and conditions.
How it works
A monitor is a high-level synchronization construct that bundles shared data with the procedures that operate on it and guarantees that only one thread executes inside the monitor at a time. Condition variables inside a monitor let threads wait for a condition with wait and be woken with signal or notify, releasing the monitor lock while waiting. Languages such as Java provide them through synchronized methods and wait and notify.
Step-by-step walkthrough
- Threads enter the monitor one at a time.
- The holder runs procedures that use the shared data.
- If a condition is not met it calls wait and joins a condition queue.
- Another thread changes the state and calls signal.
- The waiting thread resumes when the monitor is free.
Where it is used
Bounded buffers, thread-safe queues, resource managers, readers-writers solutions and state-dependent coordination between threads use monitors.
Common pitfall
Always check conditions in a while loop, not an if, because of spurious wakeups and changes by other threads. Lost notifications occur if signaling happens before waiting without a state check. Calling wait without holding the lock is an error. Nested monitor calls can cause deadlock. Keep the invariant clear and use notifyAll when unsure.
Where it fits in the course
Monitors is topic 22 of 51 in Operating Systems, rated Intermediate. It follows Semaphores. The next topic is Deadlock.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Operating Systems quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Operating Systems quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Monitors?
Where do people use Monitors?
What is the most common mistake with Monitors?
What should I learn before this topic?
How can I practice it?
Is Monitors hard to learn?
How long does it take to learn Monitors?
Which topics are related to Monitors?
What should I study after Monitors?
Related topics
- Semaphores (Operating Systems)
- Deadlock (Operating Systems)
- Mutex (Operating Systems)
- Deadlock Prevention and Avoidance (Operating Systems)