Monday, March 08, 2010

Difference between mutex and binary semaphore

I have some notes about semaphore at former post (especially at the end of that post).
Now what is the different between mutex and binary semaphore?
  • If mutex is locked by some thread, only that thread can unlock it. The binary semaphore can be unlocked by any other threads. For instance, if thread A locks the mutex and returns before release the lock, then you are in a deadlock and cannot recover it (in C). With semaphore it is a bit different. You can still release the lock even the thread A leaves early.
  • You can use recursive mutex (although you may not want to use it). This feature is not available in semaphore.
  • Priority inversion (see last post) is possible with mutex, but not applicable in binary semaphore ( I think is similar with the 1st listed item).
When using a binary semaphore to serialize the access to resource, you have to initialize it with the value 1, which means the resource is available.

No comments:

Post a Comment