It is an advance mechanism for synchronization, it is more sophisticated and advance than “Semaphore”. It can be considered as an object or module where the variables and synchronization mechanism is abstracted from the user hence unlike semaphore where user is suppose to handle the mutual exclusion and counting based logic, hence less error-prone.
It has been invented by C. A. R. Hoare, a british computer scientist who is profoundly known for inventing Quick Sort.
At a time only one thread can execute monitor’s procedure and only one of the procedure of monitor can be executed. From implementation point of view we can use binary semaphore to implement this feature of monitor .i.e. to provide the mutual exclusion among the monitor’s procedures.
Now, since only one of thread can execute the monitor hence other thread should wait for it and for waiting we need to first have the queue and then method call to make them wait () and release them from the waiting queue and having this in mind a new concept of Condition Variables is introduced. The POSIX thread implementation has library for this pthread_cond_wait() and pthread_cond_signal().
Though Condition variables’s wait() and signal() and Semaphore’s P() and V() seems similar but there are some differences:-
- Wait Queue is FIFO (hence it is considered as fair also), unlike the semaphore queue, hence process will be awake in order
- Unlike V() of semaphore, if there is no process waiting then signal() call will be nop (no operation)
- Condition variable can only be used for block and wake up, it cannot be used for counting
- Executing wait(), release mutual exclusion on the monitor i.e. allow other thread to execute it
Some caveats while implementing monitor:-
- We should call signal() as the last instruction otherwise two threads will be executing the monitor at the same time which is not what we are expecting, those two threads will be: the thread which called signal() and the one which is waked up.
- If we are calling signal in the middle then use the concept of urgent queue which is again like wait queue. The thread which is calling signal() will be inserted in urgent queue and if there is no process waiting for that signal then threads waiting in the urgent queue will be waked up and it has given priority over threads on the entrance queue (There is supposed to be an entry queue for the thread willing to get in monitor)
In the Java language, each object may be used as a monitor. (However, methods that require mutual exclusion must be explicitly marked as synchronized.) Rather than having explicit condition variables, each monitor (i.e. object) is equipped with a single wait queue, in addition to its entrance queue. All waiting is done on this single wait queue and all notify and notify all operations apply to this queue.
This approach has also been adopted in other languages such as C#.