What is a monitor in operating systems, and how is it different from a semaphore?
A monitor bundles shared data with the procedures that access it, and the language guarantees only one thread is inside at a time. A semaphore is a bare counter that the programmer must use correctly everywhere.
Explain it simply
A semaphore is like a loose key hanging by the door: anyone can take it, forget to return it, or skip it and walk in. A monitor is a room with a built-in doorman: you can only enter through the one door, and the doorman lets one person in at a time.
A monitor has:
- Private shared data
- Procedures that operate on that data
- Automatic mutual exclusion: only one thread executes inside the monitor at a time
- Condition variables, so a thread can wait inside the monitor for some state to become true
Because the compiler or runtime adds the locking, you cannot forget it.
Example
Java's synchronized keyword gives monitor behaviour:
class Counter {
private int count = 0;
public synchronized void increment() { count++; }
public synchronized int get() { return count; }
}Every Counter object has a lock. A thread entering increment() must hold it, so two increments can never interleave. With raw semaphores you would write wait/signal around count++ yourself, and one missed signal would freeze the program.
Monitors are easier and safer. Semaphores are more flexible, since signal can be called by a different thread than wait.
What to say in the interview
"A monitor encapsulates shared data and its procedures with automatic mutual exclusion plus condition variables. A semaphore is a low-level counter where correctness depends on every caller. Java's synchronized and wait/notify are monitor-style."
Common mistakes
- Thinking a monitor allows several threads inside at once.