Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor vs Mutex

I read that mutex is a semaphore with value 1 (binary semaphore) used to enforce mutual exclusion.

I read this link Semaphore vs. Monitors - what's the difference? which says that monitor helps in achieving mutual exclusion.

Can someone tell me the difference between mutex and monitor as both help achieve the same thing (Mutual Exclusion)?

like image 485
Zephyr Avatar asked Jul 02 '16 11:07

Zephyr


People also ask

Is mutex the same as monitor?

In Java terminology a monitor is a mutex lock which is implicitly associated with an object. When the synchronized keyword is applied to classes or methods an implicit mutex lock is created around the code, which ensures that only one thread at a time can execute it. This is called a monitor lock or just a monitor.

How is monitor different from semaphore?

The main difference between Semaphore and Monitor is that Semaphore is an integer variable that performs wait() and signal() operations, while Monitor is an abstract data type that allows only one process to use the shared resource at a time.

Which is better semaphore or monitor?

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.

What is the difference between a mutex A semaphore and a monitor and when would you use each?

A mutex object allows multiple process threads to access a single shared resource but only one at a time. On the other hand, semaphore allows multiple process threads to access the finite instance of the resource until available. In mutex, the lock can be acquired and released by the same process at a time.


1 Answers

Since you haven't specified which OS or language/library you are talking about, let me answer in a generic way.

Conceptually they are the same. But usually they are implemented slightly differently

Monitor

Usually, the implementation of monitors is faster/light-weight, since it is designed for multi-threaded synchronization within the same process. Also, usually, it is provided by a framework/library itself (as opposed to requesting the OS).

Mutex

Usually, mutexes are provided by the OS kernel and libraries/frameworks simply provide an interface to invoke it. This makes them heavy-weight/slower, but they work across threads on different processes. OS might also provide features to access the mutex by name for easy sharing between instances of separate executables (as opposed to using a handle that can be used by fork only).

like image 95
Vikhram Avatar answered Sep 25 '22 21:09

Vikhram