Thursday, March 24, 2011

What is the difference between mutex and semaphore?

The difference between mutex and semaphore

Semaphores can be thought of as simple counters that indicate the status of a resource. This counter is a protected from user access and shielded by kernel.If counter is greater that 0, then the resource is available, and if the counter is 0 or less, then that resource is busy.

Semaphores can be either binary or counting, depending on the number of shared resources.semaphore available accessible to all processes so that they can read and check the value and also initialize and reinitialize the value of semaphore appropriately. For this reason only the semaphore is stored in kernel so that it can be accessed by all processes.
The command
$ ipcs –s
will give the list of existing semaphores.
yoshi# ipcs -s
IPC status from /dev/kmem as of Mon Feb 7 11:21:36 2011
s 0 0x4f1c02d4 --ra------- root root
s 1 0x411c1149 --ra-ra-ra- root root
s 2 0x4e0c0002 --ra-ra-ra- root root
s 3 0x41200ec8 --ra-ra-ra- root root
s 4 0x00446f6e --ra-r--r-- root root
s 25 0x410c035b --ra-ra-ra- root root
s 26 0x712068c5 --ra-ra-ra- root root
s 2075 0x00000000 --ra------- www other
s 28 0x00000000 --ra------- www other

Mutex can be released only by the thread that had acquired it where as in semaphore any thread can signal the semaphore to release the critical section.
There are 3 major differences between Mutex and Binary semaphore.
1. In case of Mutex semaphore the task that had taken the semaphore can only give it, however in the case of binary
semaphore any task can give the semaphore.
2. Calling SemFlush() function in Mutex is illegal.
3. Mutex Semaphore can not be given from an ISR.

Apart from counting behaviour the biggest differnce is in scope of mutex and semaphore. Mutex have process scope that is it is valid within a process space and can be used for thread synchronization (hence light weight), semaphore are can be used accross process space and hence can be used for inter process synch.

Shemaphores are of two types , binary and counting.counting shemaphore can range over an unrestricted domain ,where as binary semaphore which is also known as mutex can range between 0 and 1

Links :