ChatGPT解决这个技术问题 Extra ChatGPT

Semaphore vs. Monitors - what's the difference?

What are the major differences between a Monitor and a Semaphore?

You can think of monitor as a binary semaphore.
Please go through this albahari.com/threading/part2.aspx. I read this article, best one I ever read on Threading
I 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.
Semaphore 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

A
Anthony Williams

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.


+1 Great analogy with the public bathrooms and bike rental place. I will never forget the difference between the two now.
Your answer seems to contradict stackoverflow.com/a/7336799/632951.. so who is right?
@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" greenteapress.com/semaphores
@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.
Yes, 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.
C
Community

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.


A
Andriy Tylychko

Semaphore allows multiple threads (up to a set number) to access a shared object. Monitors allow mutually exclusive access to a shared object.

Monitor

Semaphore


But, 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.
Yes what's the difference betweenn a mnitor and a mutex?
Worth noting that Semaphores don't control access to a shared object, but rather a shared resource (that will contain multiple objects).
@xbonez: If we look at java.util.ArrayList: 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.
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"
B
Billz

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)


B
Barun

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.


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.
e
e.doroskevic

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.


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.
J
JacquesB

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.