views:

925

answers:

2

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.

A: 

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.

yx
I like your analogy so far.
mrwes
Or alternatively, a semaphore is the lock on the door, while the monitor is the entire room (managed by the lock). Same idea, different perspective.
Rhamphoryncus
A: 

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.

Nick Robinson