What Is The Difference Between a Monitor And Semaphore?

Semaphores and monitors are used for thread synchronization. In a multi threaded application, it becomes essential to use a monitor or a semaphore to control the threads accessing the shared resources. If the threads are not controlled by the applications then it can result in the many problems such as the corruption of the data.

What Do I Use? A Monitor Or a Semaphore?

Semaphore and monitors both are programming constructs that are used for the synchronization of the threads. To determine what you should use out of a semaphore and a monitor, it depends on what the system and the language supports.

Difference Between a Semaphore And a Monitor

Both serve the same purpose and that is thread synchronization. However, monitors are simpler and way easier to use than the semaphores because monitors handle all details of the lock acquisition and the release. An application which runs using semaphores needs to release a lock which the thread has acquired before the application terminates, and it must be done by the application only. If it is not done by the application, then the other thread which needs the shared resource to function will not proceed further.

Another big difference while using semaphores is that each routine which accesses a shared resource needs to explicitly acquire the lock before actually using the resource. However, it is difficult to remember when coding routines that deal with multithreading. Unlike semaphores, a monitor automatically accesses the necessary locks.

Does It Cost Anything To Use a Monitor Or a Semaphore?

Yes definitely, there is a cost that has to be paid while using the synchronization constructs like semaphores and monitors. And, this cost is nothing but your time which is required to acquire the necessary locks every time a resource which is shared by multiple threads, is accessed. Also, you can make mistakes while implementing the semaphores, but there is no room for a mistake while implementing the monitors. Also, monitors need to use condition variables, while the semaphores do not need condition variables.

Leave a Reply