written 2.8 years ago by |
Both semaphores and monitors are used to solve the critical section problem (as they allow processes to access the shared resources in mutual exclusion) and to achieve process synchronization in the multiprocessing environment.
Monitor:
A Monitor type high-level synchronization construct. It is an abstract data type. The Monitor type contains shared variables and the set of procedures that operate on the shared variable.
When any process wishes to access the shared variables in the monitor, it needs to access them through the procedures. These processes line up in a queue and are only provided access when the previous process releases the shared variables. Only one process can be active in a monitor at a time. The monitor has condition variables.
Syntax:
monitor
{
//shared variable declarations
data variables;
Procedure P1() { ... }
Procedure P2() { ... }
.
.
.
Procedure Pn() { ... }
}
Semaphore:
A Semaphore is a lower-level object. A semaphore is a non-negative integer variable. The value of Semaphore indicates the number of shared resources available in the system. The value of semaphore can be modified only by two functions, namely, wait() and signal() operations (apart from the initialization).
When any process accesses the shared resources, it performs the wait() operation on the semaphore and when the process releases the shared resources, it performs the signal() operation on the semaphore. Semaphore does not have condition variables. When a process is modifying the value of the semaphore, no other process can simultaneously modify the value of the semaphore.
The Semaphore is further divided into 2 categories:
Binary semaphore Counting semaphore
Syntax:
// Wait Operation
wait(Semaphore S) {
while (S<=0);
S--;
}
// Signal Operation
signal(Semaphore S) {
S++;
}
Advantages of Monitors:
Monitors are easy to implement than semaphores. Mutual exclusion in monitors is automatic while in semaphores, mutual exclusion needs to be implemented explicitly. Monitors can overcome the timing errors that occur while using semaphores. Shared variables are global to all processes in the monitor while shared variables are hidden in semaphores.
Advantages of Semaphores:
Semaphores are machine-independent (because they are implemented in the kernel services). Semaphores permit more than one thread to access the critical section, unlike monitors. In semaphores there is no spinning, hence no waste of resources due to no busy waiting.