Looking for good analogy/examples for monitor vers

2019-07-04 16:54发布

问题:

A monitor is supposed to solve problems with semaphores in concurrent environments.
I'm looking for a good analogy using a monitor verses semaphore.

Please use information for the analogy:
4 tasks (TaskA, TaskB, TaskC, TaskD)
1 variable varX

Each Task wants to manipulate varX based on some event.

回答1:

Lets say a bunch of patients wants to go see a doctor.

A semaphore implementation would be they all stand outside the door to the office, as soon as one patient comes out, they all try to squeeze through, one person manages to get in, the rest have to wait again.

A monitor implementation would be, all incoming patients are sent to a waiting room instead, some semblance of order will be determined and when one patient is done, another will be sent to the doctor.

They are basically the same thing, monitors are just more structured than semaphores.



回答2:

You can also see a monitor as a public toilet. Once someone went in an closed the toilet door, the person inside wants no one else to be in that space (i.e. the monitor). All other people (threads) have to queue up in front of the toilet and wait (wait()). Only after the person inside has finished, it comes out and the next person can go in.

Some of the people waiting might have constipation problems. For obvious reasons, they don't want to go in or return unless they're ready to make proper use of the toilet. This is where they want to wait (wait()) until their stomach signals them (signal()) that they are ready to go to the toilet. Before this happens, they let everyone else pass.

Source: www.mijnadres.net/published/Monitor%20Object%20Pattern.pdf



回答3:

Its important to separate out the resource contention from the event notification. A Monitor and Semaphore are used to limit access to a shared resource. A monitor is basically a semaphore whose count is 1. If each of your tasks wants to get access to the single varX, then you need to protect it using your monitor (or sempahore of 1):

Monitor.Enter 
// do something with varX
Monitor.Exit

or

Semaphore.Acquire
// do something with varX
Semaphore.Release

With a Semaphore you can obviously set the number of allowed concurrenct participants to the shared resource.

Nick.