Search code examples
multithreadingoperating-systemmutexsemaphoremonitor

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)?


Solution

  • 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).