What is Monitor in OS: Definition, How It Works, and Examples
monitor is a synchronization tool that controls access to shared resources by allowing only one process to execute a critical section at a time. It uses condition variables to manage waiting and signaling between processes, ensuring safe and orderly access.How It Works
A monitor in an operating system acts like a special room where only one process can enter at a time to use shared resources safely. Imagine a bathroom with a single key: only one person can be inside at once, preventing conflicts or accidents.
Inside this room, there are special signals called condition variables. These signals let processes wait if the resource isn't ready or tell others when they can enter. This way, processes don’t interfere with each other and avoid problems like data corruption.
The monitor automatically handles locking and unlocking the room door, so programmers don’t have to manage these details manually, making synchronization easier and less error-prone.
Example
This example shows a simple monitor in pseudocode that controls access to a shared counter. It uses condition variables to wait if the counter is not zero and signals when it becomes zero.
monitor CounterMonitor {
int counter = 0;
condition canIncrement;
procedure increment() {
while (counter != 0) {
wait(canIncrement);
}
counter = counter + 1;
}
procedure decrement() {
counter = counter - 1;
if (counter == 0) {
signal(canIncrement);
}
}
}When to Use
Use a monitor when multiple processes or threads need to safely share resources like variables, files, or devices without interfering with each other. It is especially useful in situations where you want to avoid race conditions and ensure that only one process accesses critical code at a time.
For example, in a banking system, monitors can protect account balances from being changed by two transactions simultaneously. In printers, monitors help queue print jobs so they don’t get mixed up.
Key Points
- A monitor is a high-level synchronization construct in operating systems.
- It allows only one process to execute critical code inside the monitor at a time.
- Condition variables inside monitors help processes wait and signal each other.
- Monitors simplify safe access to shared resources and prevent race conditions.