Introduction To Monitors
Definition: In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true.
A Monitor is a more simple locking technique which allows resource lock between threads of a single process, while Mutex and Semaphore allow inter-process resource locking.
So it is a construct such as only one process is active at a time within the monitor. If other process tries to access the shared variable in a monitor, it gets blocked and is lined up in the queue to get access to shared data when previously accessing process releases it.
What is the difference between Semaphore and Monitor?
Both Monitors and Semaphores are used for the same purpose i.e thread synchronization. But, monitors are simpler to use than semaphores because they handle all of the details of lock acquisition and release. An application using semaphores has to release any locks a thread has acquired when the application terminates this must be done by the application itself. If the application does not do this, then any other thread that needs the shared resource will not be able to proceed.
Another difference when using semaphores is that every routine accessing a shared resource has to explicitly acquire a lock before using the resource. This can be easily forgotten when coding the routines dealing with multithreading. Monitors, unlike semaphores, automatically acquire the necessary locks.
It basically comes down to this: The monitor and the semaphore are equally expressive, meaning you can find a solution for a problem with a monitor where originally a semaphore was used and vice versa. Monitors offer prepackaged solutions to the most often used cases and carry with them most of the advantages of object-oriented programming (i.e., you know the only way to mess with the variables managed by the monitor is through its operations). The disadvantage is that they can't be retrofitted easily into non-object-oriented languages, and plain object-oriented languages will leave their use optional.