Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


Some of My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET

Shahed Khan blog
Source: http://koti.mbnet.fi/niclasw/MutexSemaphore.html

Mutex vs. Semaphore, what is the difference?

The Toilet Example  (c) Copyright 2005, Niclas Winquist ;)

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.

Officially: "Mutexes are 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."
Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, 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.

Officially: "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)."
Ref: Symbian Developer Library
Posted on Friday, June 9, 2006 4:59 AM | Back to top


Comments on this post: Difference between Mutex and Semaphore

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
A mutex is owned by a thread/process. So once a thread locks it, then other threads/processes will either spin or block on the mutex. Whereas, semaphore allows one or more threads/processes to share the resource.

pthread_mutex_lock(&mutex_obj)
global_data;
pthread_mutex_unlock(&mutex_obj)

here, you are locking global data so that only one thread/process can access it. Others will wait in a turnstile forming a Q.
while in semaphore you can define that how many concurrent threads/processes can access that resource at a time.
so if a psuedo code is like this

sema(10) // ten threads/process have the concurrent access.

sema_lock(&sema_obj)
global_data
sema_unlock(&sema_obj)

then max 10 threads/processes will access it.
when one process locks the semaphore the counts decrements by 1. So when the count=0, all the processes are using the data.

So you can see that a binary semaphore is like a mutex.
Left by Senthil Kumar N on Sep 06, 2006 2:05 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
semaphores are different it is nothing but the cumulative flags for the resources, whenever any resource is busy then the count in the semaphore has been dicremented this will happened till it decrement to zero. the consumers required any resouce wait till the count in the semaphore has been incremented.
Left by vishwa on Oct 07, 2006 6:40 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Perhaps somebody can confirm, my understanding comes mostly from observation. It seems that there is fundamental difference between a binary semaphore and a mutex in that a mutex is tied to the thread that takes it. ie, only the thread picking it up can let it go. A binary semaphore can be released by other threads. Consider I/O examples, We pickup a semaphore to wait for some kind of I/O, when our Rx, task picks up the byte, the Rx task releases the same semaphore. This cannot be done with a mutex. Can someone please confirm this since the answer to the question is still not completely clear.
Left by Kartik Aiyer on Nov 27, 2006 9:31 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
By the explanation of Niclas Winquist, we can say mutex is equivalent to binary semaphore.
Left by Prashanth on Dec 14, 2006 5:33 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
from the above description, I think if i make the key number =0 in semaphore then it becomes mutex. So also semaphore description is not clear.
Left by M. Neehar on Jan 22, 2007 8:43 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Kartik is right about the difference between mutex and binary semaphore. But this difference exist for perticuler "type" of mutex. If we create a mutex object with type as "errorcheck" then mutex lock will be unlokced by only the thread which locks it. API is given below:
pthread_mutex_t mutex=PTHREAD_ERRORCHECK_MUTEX_INTIALISER_NP
lock created by muxtex object will check that if same thread has locked it or not.
Left by Tej on Jan 29, 2007 2:19 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
As I understand, Mutex is the "policy' to get mutual execution and semaphore is the "mechanism" to acheive mutual execution.Please correct me if I am wrong
Left by Neetu on Jan 29, 2007 11:26 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Everything is nice. but can any body explain, in an application, on what basis we chose one of these semaphore and mutex..
Left by Prashanth on Jan 30, 2007 8:06 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
As both are used for synchrnization...but wat is the main difference in between these two is still not clear
Left by Chhavi on Mar 09, 2007 10:01 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
And, in keeping with your toilet metaphor, a deadlock is a bad case of constipation.
Left by Some Dude on Mar 15, 2007 2:22 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Read Fundamentals of Operating Systems, Third Edition by A.M. Lister, Page 19. Great book and all of you guys need to read this. "Mutex is the name of a Semaphore".
Left by Lister on Mar 28, 2007 3:14 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
I think mutex is nothing but semaphore with value 0
Left by sukant on Mar 30, 2007 9:24 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
there is a big difference of change in priority for the mutex and semaphore. the way there are initilized are different.
Left by ARUN on May 07, 2007 11:18 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
nice example

Thanks
Left by some dude on May 11, 2007 7:33 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...

i had a doubt that whenever we post the semaphore it is actually unlocking the semaphore
i feel , that means the same thread is actually unlocking the semaphore ???
please explan
Left by vijay on May 15, 2007 7:31 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
We actually mean a semaphore is nothing but a counting semaphore and by mutex we actually mean a mutex semaphore. A mutex is essentially a binary semaphore. You can replace any Mutex with a Semaphore of MaxCount 1.

Mutexes are usually more efficient than binary semaphores.

Mutex has an owner concept, i mean unlocking a mutex can be only done by the thread that locked (or, equivalently, "owns") the mutex.



Left by Biki on May 28, 2007 10:40 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
I am just concluding the discussion.
theoretically, Mutex & Binary Semaphore are same but practically, mutex can be release by the task who acquired it (because that task has got ownership after acquiring it). In case of binary semaphore (or semaphore) can be release by any other task also, does not matter who acquired it.
Left by Rajiv Nigam on Jul 02, 2007 4:29 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
One difference is owner ship. WHile a locked mutex should be released by the same thread WHile a thread can post to the semaphore
Left by R. Chandra Sekhar on Jul 26, 2007 3:51 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
I am not sure, but, I think one more difference between Mutex and Semaphoe is

We acquire a mutex lock when we need to access global data to make only one thread
access the data in multithreaded environment.

We acquire a semaphore lock when we need to access global data to make only one
process or restricted number of process can access the data in multiprocess environment.

Thanks
Sudhakar
Left by Sudhakar on Sep 11, 2007 8:13 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
To my mind the real difference between a semaphore and a mutex is that a semaphore is the structure proposed by Hoare many years ago as a general mechanism structure whereas a mutex is a special case of a mutual exclusion lock. You can make a mutex from a semaphore but not a semaphore from a mutex.

Semaphores have the other feature of being named so that they operate between processes. Mutexes are limited to serializing the threads within one process.

Another form of mutual exclusion lock is a spinlock which is basically the process of polling a test and set machine instruction. It is used for very fine grained locking where the overhead of the polling is either irrelevant, such as with a multiple processor machine or where the polling overhead is less than the mutex setup overhead or where a very small latency is critical.

A mutex comes at a surisingly high cost. You might sacrifice up to 5-10% of performance to the locking overhead.
Left by Johns on Sep 19, 2007 8:43 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Ur answer is really good. Even non computer science student also underastand with ur example .so,keep on answer......!
Left by sivashankar on Oct 17, 2007 6:05 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Plz all of you puts yur hands together


Left by Ash on Jan 10, 2008 12:57 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
-->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).
-->Mutexes are 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.
Left by vijay on Jan 21, 2008 11:24 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...

i have doubt on difference between semaphore and mutex?
Left by vijay on Jan 21, 2008 11:26 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
good example
thanx
Left by mahesh on Apr 04, 2008 9:31 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
A very nice example followed by a great discussion!
It solved all the doubts I had.
Thanks a ton!
Left by Anuprit on Apr 06, 2008 9:48 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Mutex is a binary semaphore
Left by pradeep on Apr 06, 2008 9:58 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...

Good Example....

Thanks
Shashidhara HN
Left by Shashidhara HN on May 14, 2008 6:45 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
You got semaphore in my mutex.
No YOU got mutex in MY semaphore.
Left by Harry Burnett Reese on May 15, 2008 7:18 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
To hold the mutual exclusion we use mutex and offcourse to serialized the execution we use semaphore.Both semaphore and mutex are integer variables.
Left by Yasir Imtiaz khan on May 16, 2008 6:55 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
here I stand in that vast crowd of hungry philosophers shiveringly awaiting the announcement of the switching of the great big mutex blasting from the speakers on the wall. All around me tiny semaphores are counting up and down. Outscht!! Who has given forks to theese hungry guys? Fortunately they do not need the key to the toilet, because they did not eat for days.
Left by John Michael Duillont on May 27, 2008 10:34 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
How are Mutex and Semaphores implemented to control the resources?
What resources can be locked using a semaphore?
Left by Priyanka on May 30, 2008 4:38 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Differences between Mutex and Binary Semaphore.
Mutex is actually an extension of binary semaphore with some extra features. If we are not using the extra features, this can be considered as a binary semaphore.
Differences are
1. If Mutex is acquired by some process, only that process can unlock it, where as a binary semaphore can be unlocked by any other process

2. In mutex, recursive calling is possible, where as this feature is not available in binary semaphore.

3. Priority inversion is possible with a mutex semaphore. The same is not applicable in case of binary semaphore
Left by Akhil Chandran on Jun 11, 2008 5:18 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Sorry guys, last one was Priority inheritance!! Sorry for the mistake!!
Left by Akhil Chandran on Jun 11, 2008 5:40 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
In windows OS the mutex has few additinol features over a binary semaphore .
A mutex protect a thread from getting deadlocked due to reentrancy. This is achieved because the same thread can acquire the mutex any number of times. It should also release it the same number of times it has been acquired. Also APC delivery to the thread are disabled when the mutex is acquired.However Special Kernel Mode APC's can still be delivered to a thread even after mutex is acquired.This is where reentrant acqusition of mutex can happen.
Left by Rajeev on Jun 12, 2008 3:31 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Hai,

thanks for providing the information between Mutex and Semaphore

Ramesh Nakarikanti
Left by Ramesh Nakarikanti on Jun 26, 2008 3:47 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
the difference between mutex and binary semaphore. But this difference exist for perticuler "type" of mutex. If we create a mutex object with type as "errorcheck" then mutex lock will be unlokced by only the thread which locks it. API is given below:
pthread_mutex_t mutex=PTHREAD_ERRORCHECK_MUTEX_INTIALISER_NP
lock created by muxtex object will check that if same thread has locked it or not
Left by umesh on Jun 30, 2008 8:18 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Nice answers i got the difference..
Left by babu on Jul 15, 2008 7:22 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Thanks for your valuable inputs guys. it clarified my doubts.
Really thanks for every one.

Regards,
Santha
Left by Santharam V on Aug 07, 2008 7:02 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Thanks so much!!^-^
Left by Nicholas on Aug 14, 2008 4:00 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
As somebody already stated, semaphores are general solution that is widely used e.g for IPC (vide systemV semaphores implementation) while mutex is (basically binary semaphore) used for thread synchronization and as already stated there mutex is associated with it's owner.
Left by GiM on Aug 25, 2008 5:22 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
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).
-->Mutexes are 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
Left by sahadev on Aug 26, 2008 5:25 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
• Re: How to check if a mutex is still locked?
... Shared resource should only be handled inside critical regions ... particular mutex mentioned in the initial message. ... lock the_super_mutex ... unlock the_super_mutex ...
(comp.programming.threads)
• Pthreads: how to insure mutex is unlocked when a thread dies.
... Anyway, I was planning to have this thread lock a mutex when it starts, ... unlock it when it's done, e.g., when the application notifies it to ... I'm concerned that if the thread dies before the application notifies ...
(comp.programming.threads)
• Re: double-checked locking in C
... Except that threads may never lock the mutex. ... guarantee they'll ever see the initialization. ... you don't call 'lock' or 'unlock' if the initialization ...
(comp.programming.threads)
• Re: Terminology?
... static lock ... you just mean mutex, see below. ... lock, a spinlock, a semaphore, etc... ...
(comp.programming.threads)
Re: [PATCH 1/19] MUTEX: Introduce simple mutex implementation
... > a mutex was a sensible implementation tradeoff. ... are really counting semaphores, ... >> acceptable patch that introduces a separate data structure. ... > general semaphore, because a mutex has stronger invariants. ...
Left by Sahadev Tarei on Aug 26, 2008 5:34 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Thanks guys... i learnt Mutex & Semaphore
Left by Saravana on Aug 28, 2008 3:46 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
hi thanks
Left by chandra on Sep 10, 2008 6:29 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Thanks, you explained the difference, the simplest way possible!
Left by Mortaza Doulaty on Sep 16, 2008 7:43 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
found similar information on the net...thought of sharing here!!

http://www.netrino.com/node/202
Left by Abhik on Sep 24, 2008 7:18 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...

Above link seems to be not working

http://www.netrino.com/node/202 9/24/2008
page not found .
Left by friend on Oct 05, 2008 3:50 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
From experience and comments it seems the most important distinction to make is that a mutex protects a particular section of code run by a single thread (thus limiting it to 1 holder), while a semaphore protects access to a resource, however that resource is managed.

Left by wtg on Nov 24, 2008 5:35 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Consider we create a semaphore for "3" resources. Out of "3", if "1" resource is being used used, then How to find out free resources ? Because we dont know which resource is being used ?
Left by Gopu on Dec 08, 2008 4:55 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
There are differences and there are none. It all depends in the context and usage of these words. In text books they both refer to the same general concept -- controlled access to shared resource.

In practice and implementation, there are some real differences (Under Unix/Linux).

Semaphore: A system wide mutual exclusion object and comes in two flavors, 1) binary (allow only one user at a time), and 2) counting (allow at most N users). There are two kinds of them based on how you create them, 1) System V semaphores and 2) POSIX semaphores. They are functionally same (more or less) but the system calls to create and use them are different.
The following are the prominent properties:
a) Semaphore operations have built-in wait and wakeup semantics,
b) they have a system wide existence in their own namespace (like file, devices etc)
c) they are created and used with system call,
d) they are (at least System V ones) "counting" by default can be used as binary ones
e) usually used for process synchronization (Inter Process Communication)

mutex: POSIX threads and native threads libraries provide mutex objects. They are process private and they have "one at a time" semantics and require something else to use.
The following are the prominent properties:
a) library provided objects/operations (created and used with the help of relevant library calls)
b) require a separate object (condition variable) to properly implement mutual exclusion ,
c) they are process private, have no presence in the system namespace but can be made system wide by creating them in shared memory
3) usually for in-process synchronization
Left by mr_smith on Dec 11, 2008 9:28 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
I think mutex is text locking mechanism and semapphore is data locking mechanism
Left by srividya on Dec 17, 2008 6:26 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Hi All,

After researching on this topic i found following information let me know if it is correct?

Binary semaphores and mutex have difference though both are different ways of acheiving the thread synchronization and concurrent access of resources without deadlocks or conflicts

Binary semaphores differs from mutex in two ways though most of the systems don't differentiate between these two --

1) Ownership - In case of mutex only the owner thread can lock it and only that can release it. For a thread only two states are possible - owned and unlocked as it is used for serialization basically. Where as binary semaphore is locked and unloacked also other threads can do sem_post() and if signaled by owner thread as available can be occupied. So it is used for basically signalling.

2) Recursive Access - Mutex can be recursively locked by same thread so though it has to be released by thread same number of times. In case of binary semaphore it is not possbile.

I am not able to find a good implementation of these two so that i can see these suttle differences though found many explainations about these two please if some one know any system where these two differences can be found clearly using some examples would be great to post for all...

It is also said that semaphore are costly in implementation but safer to do this. Also it is said that in case of semaphores there is seperate monitor for keeping track...

A very good explaination given by following link -

http://vodoom.wordpress.com/2008/09/24/difference-between-binary-semaphore-and-mutex/

Regards,
Jain
Left by Jain on Jan 31, 2009 4:19 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
After going through this great discussion , I grab some points like.

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).

Semaphore can be Binary,Mutex and couting .
So as per functionaltiy Binary semphore as similar to Mutex .

So we can say

semaphore ->Binary semaphore
semaphore ->mutex
semaphore -> counting semaphore.

Now difference comes in picture is the one :

Ownership :
In mutex , it can be released by the same thread/process which has quired it .
In binary : It can be released by any other thread/process also.

So we can say that a semaphore can be binary and mutex , but there is major difference in the ownership.
Left by Gaurav Jain on Feb 16, 2009 5:55 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Gud example of mutex and semaphore
Left by ashutosh kumar bharati on Mar 05, 2009 6:35 AM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
i realy got the diff b/w mutex and binary semaphore.
Left by ardhanareesh on Mar 13, 2009 11:27 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
i didnt got clear concept of mutex....
Left by pankaj huria on Mar 20, 2009 8:27 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
please give me another example
Left by shalini rawat on Mar 20, 2009 8:42 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
A mutex is a binary semaphore, usually including extra features like ownership or priority inversion protection. The differences between mutexes and semaphores are operating system dependent. Mutexes are meant to be used for mutual exclusion only and binary semaphores are meant to be used for event notification and mutual exclusion.
Left by BLACK!MIRR0R on Mar 23, 2009 6:17 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
hi, the dicussion cleared my doubts.
thanks to evryone
Left by sofia on Apr 09, 2009 1:46 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...

A good example , can be easily remembered.
Left by Pradeep pani (NIIT Technologies) on Apr 13, 2009 3:16 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
I thing a main difference Between Mutex and Semaphore is In case of mutex when a thread/process got stuck in lock i.e. mutex variable is busy ,the waiting process is actually in running state waiting continuousle for the lock to get free.
Whereas in case of Semaphore , the waitinh process is blocked(releasing the cpu)instead of running and wakesup when semaphore is incremented by one.
Left by Rajwinder Kaur on Aug 26, 2009 9:30 PM

# re: Difference between Mutex and Semaphore
Requesting Gravatar...
Mutex is a binary semaphore.

Semaphore is two types - binary and counting

Mutex- Sharing is not possible
Semaphore- sharing by multiple users.
Left by Rasmi Mishra on Sep 15, 2009 3:50 AM

Your comment:
 (will show your gravatar)
 


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net | Join free