Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Semaphore and Mutex with respect to Priority Inversion ( and also, perhaps, priority inheritance )

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 )

like image 620
aknon Avatar asked Oct 30 '25 23:10

aknon


1 Answers

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.

like image 118
Aleksandr Pakhomov Avatar answered Nov 01 '25 13:11

Aleksandr Pakhomov