Monday, November 29, 2010

Mutex vs Semaphore

Tip  : Mutex and semaphore has some behavior mismatch is there in certain scenarios.
Details : Most of us are familiar with both mutex and semaphore.  These objects are used for synchronize the code flow and properly handle the shared resource used in our code flow. Now we can check the major difference between mutex and semaphore.
Mutex:
Is a key to a shelf. One person can have the key to use the shelf at the time. When his usage is finished, the person gives (frees) the key to the next person in the queue.
Theoretically: "Mutexes are typically used to serialize 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:
It is the number of free identical shelf keys. Example, say we have four shelves 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 there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the shelf, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Theoretically: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)."
Some of the document we can find the single semaphore is equal to mutex. But in certain scenarios behavior of mutex and semaphore are different.
1.       Within single thread, we can create more than one mutex without release the previous handle. But if we use single semaphore, second semaphore will not create properly and it will wait for previous semaphore to release its handle. So if we need to synchronize recursive calling sequence, it is better to use mutex instead of semaphore. Otherwise there is some chance for dead lock and all.
2.       Suppose one application is waiting for second application to release a particular semaphore. During that waiting time if second application terminated abnormally. In this case semaphore will not signal the waiting client about the semaphore release information. In case of mutex, waiting application will get the return code as ‘WAIT_ABANDONED’ during the locked application abnormal termination time.

Reference    :

Posted By :Arun M. S.

No comments:

Post a Comment