Sunday, November 13, 2011

Mutexes VS Semaphore

Mutex: Mutex is a program object that is typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section."

Semaphore: A semaphore is like an integer, with three differences:
  • When you create the semaphore, you can initialize its value to any integer, but after that the only  operations you are allowed to perform are increment (increase by one) and decrement (decrease by one). You cannot read the current value of the semaphore.
  • When a thread decrements the semaphore, if the result is negative, the thread blocks itself and cannot continue until another thread increments the semaphore.
  • When a thread increments the semaphore, if there are other threads waiting, one of the waiting threads gets unblocked.
To say that a thread blocks itself is to say that it notifies the scheduler that it cannot proceed. The scheduler will prevent the thread from running until an event occurs that causes the thread to become unblocked. In the tradition of mixed metaphors in computer science, unblocking is often called  as€œWaking.

From the definitions, it is very much clear that mutex contains binary value either True or False but a semaphore contains an integer value which holds those many number of keys to get that resource.

To further understand these two, lets consider an example
  • Mutex is a key to a toilet. One person can have the key - occupy the toilet-at the time. When finished, the person gives (frees) the key to the next person in the queue.
  • Semaphore on the other hand is analogous to the he number of free identical toilet keys. Say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
One of the often asked question is "what is the difference between a mutex and a binary semaphore?"
  By binary semaphore I mean that the value store in the semaphore is 1. So its similar to the mutex. But there are quiet a few good characteristics that distinguish the two.
  • Mutexes can be recursive (so reentrant lock works), and Semaphores are not.
  • One significant difference - a semaphore may be procured and vacated by any thread in any sequence (so long as the count is never negative), but a mutex may only be unlocked by the thread that locked it. Attempting to unlock a mutex which was locked by another thread is undefined behavior
  • The Mutex class enforces thread identity by virtue of owners, so a mutex can be released only by the thread that acquired it. In contrast, the Semaphore class doesnot enforce thread identity.

Now lets understand what are recursive mutexes:
POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be POSIX conform, they have to.

Now, you may ask why on the earth would I call lock on the same mutex. To find the answer please refer links 1 and 2. It has pretty good explanation and I dont want to duplicate the effort.

There is something called as Futexes aswell, these are Fast user level mutexes, pthread library on linux implements Futexes, so all your user level programs that spawn thread are already using Futexes. Futexes have an edge over mutexes and hence are very useful.

[] http://stackoverflow.com/questions/2415082/when-to-use-recursive-mutex
[] http://stackoverflow.com/questions/187761/recursive-lock-mutex-vs-non-recursive-lock-mutex
[] http://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-2-the-mutex/
[] http://web.itu.edu.tr/kesgin/mul06/intel/instr/cmpxchg.html