What are the major differences between a Monitor and a Semaphore?
-
10You can think of monitor as a binary semaphore. – Maxim Egorushkin Sep 07 '11 at 14:55
-
similar: http://stackoverflow.com/q/3547030/158779 – Brian Gideon Sep 07 '11 at 15:33
-
2Please go through this http://www.albahari.com/threading/part2.aspx. I read this article, best one I ever read on Threading – Shantanu Gupta Sep 08 '11 at 10:08
-
7I don't think you're right, Maxim. A semaphore is "lower-level" structure, if I'm not mistaken, whereas a Monitor is an full-blown object. I remember that we went over monitors briefly in my Operating Systems class in college, but I don't remember how a Monitor differed from a Mutex, aside from it being object-oriented. I remember one problem could be done using monitors, but we couldn't use this same method in class, due to the restrictions of the C language. – user919860 Oct 14 '11 at 19:27
-
2Semaphore and Monitor are very difference, yet equivalent in power, in the sense that you can implement one from another. You can read Hoare's original paper that proves their equivalence from [here](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC4QFjAA&url=http%3A%2F%2Fjohn.cs.olemiss.edu%2F~dwilkins%2FSeminar%2FS05%2FMonitors.pdf&ei=C1KFT4ypAozqrQe-kqWxBg&usg=AFQjCNHsqKHJRPfPyD7DiRxovfuud2jshw&sig2=xRt4RdUf4cSVOCR9A5AEzg) – Thanh DK Apr 11 '12 at 09:45
-
A semaphore is a special case of a monitor--one whose operators are V & P (signal & wait, etc). What particular things in a particular language/library go by these names depends on the language/library. – philipxy Jul 04 '17 at 09:19
-
1@MaximEgorushkin You mean a mutex is a binary semaphore. – philipxy Jul 04 '17 at 09:35
7 Answers
A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished.
A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter.
If the counter is already zero when a thread tries to acquire the semaphore then it has to wait until another thread releases the semaphore. If multiple threads are waiting when a thread releases a semaphore then one of them gets it. The thread that releases a semaphore need not be the same thread that acquired it.
A monitor is like a public toilet. Only one person can enter at a time. They lock the door to prevent anyone else coming in, do their stuff, and then unlock it when they leave.
A semaphore is like a bike hire place. They have a certain number of bikes. If you try and hire a bike and they have one free then you can take it, otherwise you must wait. When someone returns their bike then someone else can take it. If you have a bike then you can give it to someone else to return --- the bike hire place doesn't care who returns it, as long as they get their bike back.

- 66,628
- 14
- 133
- 155
-
190+1 Great analogy with the public bathrooms and bike rental place. I will never forget the difference between the two now. – Drupad Panchal Sep 07 '11 at 15:40
-
4Your answer seems to contradict http://stackoverflow.com/a/7336799/632951.. so who is right? – Pacerier Dec 08 '11 at 15:45
-
6@Pacerier: I am :-) The only contradiction is the high-level/low-level thing. You **can** build a monitor from semaphores, it's just not very tidy, precisely **because** a monitor is a higher-level structure than a semaphore. A semaphore is just a counter with waiting. I suggest reading "The Little Book of Semaphores" http://greenteapress.com/semaphores/ – Anthony Williams Dec 09 '11 at 08:02
-
@Anthony Williams: You're definitely right. I only selected Brian Gideon's answer by mistake, and the forum wouldn't let me change my selection. I had to e-mail the moderators to help me change my selection, because I hated his answer. Your answer is the best. I now choose your answer. – user919860 Jan 04 '12 at 17:53
-
3@AnthonyWilliams: I perhaps doubt the notion that you can only build monitors from semaphores. The other way is also possible and because of that we can't profusely say that monitor is a higher level entity than semaphores. – Kavish Dwivedi Mar 23 '13 at 06:36
-
6Yes, you can build a semaphore from a monitor. You can always build low level objects from high level ones. The high/low level stuff is about capabilities and scope of operation, not about which can be used to build the other. – Anthony Williams Mar 23 '13 at 11:44
-
Also with the semaphore analogy, the framework just provides a way of informing to the bike hire place that somebody has returned a bike. Now sometimes even those guys who haven't hired any bikes from your bike store might send a message that they are returning their bikes. Also sometimes a person can send an incorrect count of bikes while returning their bikes. So the bike hire store manager might need to deploy some facility that will ensure that the counts are right. Or he might think his store has magically produced more bikes than he originally had. – Chan Mar 07 '14 at 22:22
-
1@Chan AFAIK that would be impossible, at least in windows. _the max number of bikes_ is the semaphore's max count and is fixed since the semaphore is created. – Chaplin89 Jun 19 '14 at 15:08
-
I don't know about window's semaphores, but in Java the API does not provide you any support for making sure the number of permits do not exceed the number of permits you initially created the semaphore with. You've got to build that logic yourself. I think it was done to resolve things like deadlock. – Chan Jun 20 '14 at 17:44
-
As far as I understand semaphores, it does not allow you to solve the bike hire problem. Semaphores will guarantee that only 50 client will start picking up bikes at a time, but does not guarantee that two clients do not take the same bike. I mean that bikes need extra synchronization, for example monitor. In other words, semaphores do not solve the problem of assignment. It can only solve the problem of capacity, e.g. "There can be at most 4 persons in the lift" or "There can be no more than 10 concurrently logged-in uses". – dma_k Mar 29 '16 at 16:39
-
@dma_k My analogies are simplified. If your real operation has multiple parts, you need to ensure they are all correctly synchronized. – Anthony Williams Mar 30 '16 at 10:06
-
it feels like you compare mutex (binary semaphore) with the semaphore, rather than monitor vs semaphore. – denis631 Oct 30 '18 at 11:48
-
A bike-hiring place would just be like an array of mutexes, since each customer would have exclusive access to a bike until returned again. A semaphore does not have the concept of exclusive ownership. Semaphores are a device used for signling, not for locking. – JacquesB Nov 03 '20 at 12:02
-
@AnthonyWilliams your definition of a monitor seems to differ from wikipedia’s one https://en.wikipedia.org/wiki/Monitor_(synchronization). According to that definition, a semaphore is a particular kind of monitor. – Manuel Selva Mar 23 '22 at 05:43
-
You can implement a semaphore with a monitor, and indeed it may technically count as a specific instance of the concept, but that's backwards: a semaphore is a lower level concept. – Anthony Williams Mar 24 '22 at 08:09
Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.
The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.
A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.
Link: here for further reading. Hope it helps.

- 1
- 1

- 1,834
- 22
- 36
Semaphore allows multiple threads (up to a set number) to access a shared object. Monitors allow mutually exclusive access to a shared object.

- 15,967
- 6
- 64
- 112

- 869
- 8
- 12
-
10But, then how would a Monitor differ from a MutEx? A mutual exclusion lock does the same exact thing as a a semaphore, but only allows one thread to access the Critical Region at a time. – user919860 Oct 14 '11 at 19:24
-
2
-
2Worth noting that Semaphores don't control access to a shared object, but rather a shared resource (that will contain multiple objects). – Ayush Oct 15 '12 at 16:45
-
@xbonez: If we look at [`java.util.ArrayList`](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html): is it an object or container of multiple objects? Well, it is both at the same time. So is semaphore appropriate to control access to it? I would say: no. – dma_k Mar 31 '16 at 07:45
-
In the accepted answer itself it is mentioned that Monitor is implementing the Mutual Exclusion. Please see "The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time" – achoora Jul 05 '16 at 10:56
One Line Answer:
Monitor: controls only ONE thread at a time can execute in the monitor. (need to acquire lock to execute the single thread)
Semaphore: a lock that protects a shared resource. (need to acquire the lock to access resource)

- 7,879
- 7
- 33
- 35
A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal()
on the semaphore when a file is downloaded. The consumer calls wait()
on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.
A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait()
can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.
A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.
A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized
keyword. The synchronized
keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.

- 41,662
- 13
- 71
- 86
Semaphore :
Using a counter or flag to control access some shared resources in a concurrent system, implies use of Semaphore.
Example:
- A counter to allow only 50 Passengers to acquire the 50 seats (Shared resource) of any Theatre/Bus/Train/Fun ride/Classroom. And to allow a new Passenger only if someone vacates a seat.
- A binary flag indicating the free/occupied status of any Bathroom.
- Traffic lights are good example of flags. They control flow by regulating passage of vehicles on Roads (Shared resource)
Flags only reveal the current state of Resource, no count or any other information on the waiting or running objects on the resource.
Monitor :
A Monitor synchronizes access to an Object by communicating with threads interested in the object, asking them to acquire access or wait for some condition to become true.
Example:
- A Father may acts as a monitor for her daughter, allowing her to date only one guy at a time.
- A school teacher using baton to allow only one child to speak in the class.
- Lastly a technical one, transactions (via threads) on an Account object synchronized to maintain integrity.

- 1,520
- 2
- 12
- 18
-
I think that traffic light on the road cross is also a binary flag: either cars on one road or on orthogonal road can drive (mutually exclusive) hence example (3) is the same as (2). Also I think that those examples are corner case for semaphores (trivial case), which can be implemented using monitor. There are more typical examples in [wikipedia](https://en.wikipedia.org/wiki/Semaphore_%28programming%29#Examples). – dma_k Mar 31 '16 at 07:34
When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.
In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.
A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.
Taken from The Open University M362 Unit 3 "Interacting process" course material.

- 2,129
- 18
- 25
-
Except that, although semaphores are quite commonly made available in a language and presented in textbooks as a kind of variable with limited atomic operators, a semaphore is *a special case of a monitor*--*because* it is a kind of variable with limited atomic operators, because that's what a monitor is. The arguments above that semaphores are "lower level" are specious. – philipxy Jul 04 '17 at 09:11