4

Well this topic isn't as simple as it appears. As we know a mutex can be implemented by a Semaphore with initial count=1.
But going through a few articles, I also found that tremendous amount of efforts has gone into separating these two, and treating mutex as a separate concept different from a semaphore
Problem of Priority Inversion, which has lead to a new concept of priority inheritance, somewhat appear confusing to me.

Also some people speak of mutex with respect to ownership ( as it appears in what-is-mutex-and-semaphore-in-java-what-is-the-main-difference ). Well ownership is bad term. In no way , Mutex is an owner of a shared resource. Holding a Lock and Releasing a Lock, are effectively a way of signalling, perhaps like, *Hey wait !! Till I complete and signal you*

Looking for some concrete reasons that has lead to a separation of Mutex from a Semaphore ( with initial count = 1 )

Community
  • 1
  • 1
aknon
  • 1,408
  • 3
  • 18
  • 29

2 Answers2

3

Ownership means you cannot lock mutex in one thread and release in another. So semaphore is more universal. You can do dumb mutex realisation with just a semaphore but you can't do semaphore with JUST a mutex.

Priority inversion is a following situation:

1) high priority thread A waits for mutex

2) low priority thread B holds it but couldn't execute until it releases it cause

3) mid-priority thread C occupies CPU

To handle such situation scheduler should have some logic:

to start A sooner allow B to execute instead of C

To understand that it is B who stop A it have to know mutex owner. For semaphores it is impossible to say who unlocks it: B or C. So no way to perform such kind of logic.

Aleksandr Pakhomov
  • 753
  • 1
  • 5
  • 13
  • Yes your are right. For priority inheritance to work, thread B will temporarily inherit the priority of the higher-priority thread A. Essentially just a `conditional variable`, such as `semaphore` is not always enough. Though a `mutex` can be simulated with a semaphore but only for limited set of scenarios. For E.g: `recursive mutex` and `monitors` are more complicated to be implemented just by a `semaphore`. Also I found this link very useful : http://en.wikipedia.org/wiki/Condition_variable#Condition_variables – aknon Jan 07 '14 at 06:11
0

Mutexes in Java (both in forms of intrinsic locks and java.util.concurrent.Lock) are nicely combined with event notification mechanism. Implementing such a full-blown mutex by Semaphores is problematic: it requires releasing one semaphore and acquiring another one as an atomic transaction.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
  • Well, not sure of what you are saying.. I mean in terms of `event notification mechanism`. But anyways the questions is a general one, not related to a specific programming language. You see what I am saying, - are you attaching the meaning and differences of `mutex` and `semaphore` with respect to Object Oriented Programming ? – aknon Jan 06 '14 at 16:31