Is it better to synchronize with semaphores or with monitors?

farm ostrich picture farm ostrich · Feb 22, 2011 · Viewed 16.2k times · Source

Is it better to synchronize with semaphores or with monitors?

Answer

JYelton picture JYelton · Feb 22, 2011

"Better" depends on context. They are "equally powerful" according to James McParlane. I highly recommend viewing his blog for a discussion on the differences.

Here is a quick guide I found:

Semaphores

  • Can be used anywhere in a program, but should not be used in a monitor
  • Wait() does not always block the caller (i.e., when the semaphore counter is greater than zero).
  • Signal() either releases a blocked thread, if there is one, or increases the semaphore counter.
  • If Signal() releases a blocked thread, the caller and the released thread both continue.

Condition Variables

  • Can only be used in monitors
  • Wait() always blocks the caller.
  • Signal() either releases a blocked thread, if there is one, or the signal is lost as if it never happens.
  • If Signal() releases a blocked thread, the caller yields the monitor (Hoare type) or continues (Mesa Type). Only one of the caller or the released thread can continue, but not both.

This information from: http://www.cs.mtu.edu/~shene/NSF-3/e-Book/MONITOR/sema-vs-monitor.html

Some useful resources: