Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to synchronize with semaphores or with monitors?

Is it better to synchronize with semaphores or with monitors?

like image 262
farm ostrich Avatar asked Feb 22 '11 20:02

farm ostrich


1 Answers

"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:

  • What is a Semaphore
  • Looking for Good Analogy Examples for Monitor Versus Semaphore
  • What are the differences between various threading synchronization options in C#?
like image 84
JYelton Avatar answered Oct 13 '22 00:10

JYelton