Friday, July 3, 2020

Mutex vs Semaphore vs Spinlock

Why Mutex can not be used in ISR

Mutex & Semaphore can sleep so can not be used in ISR
Use Spinlock in ISR. SpinLock coninuously check the lock in light loop

Use of Spinlock in single CPU system 

To use spin lock in single CPU system. Need to disable kernel preempt after acquiring lock & enable that after releasing lock

Difference between Mutex and Semaphore




1) Mutex only one can acquire. Rest will be in locked.
In Semaphore N number of process can acquire.
In Binary semaphore only 1 can acuire.

2) Semaphore will be releases in same order it went in wait state.
In Mutex there is no gurantee for order of unlock

3) Binary semaphore can be used as mutex. But mutex can not be used as semaphore

4) Semaphoe add more memory footprint in program space compare to mutex.

5) Mutex can be unlocked by same thread only which has locked it.
 Semaphore can be unlocked by other process/thread also.

One more issue can happen with mutex https://stackoverflow.com/questions/37860811/do-mutexes-guarantee-ordering-of-acquisition

1 comment: