views:

2584

answers:

2

What is the difference between semaphores and mutex provided by pthread library ?

+7  A: 

semaphores have a synchronized counter and mutex's are just binary (true / false).

A semaphore is often used as a definitive mechanism for answering how many elements of a resource are in use -- e.g., an object that represents n worker threads might use a semaphore to count how many worker threads are available.

Truth is you can represent a semaphore by an INT that is synchronized by a mutex.

Hassan Syed
setting the counter to 1 (whatever value that represents) the semaphore becomes a mutex
stacker
cppdev
No see http://www.opengroup.org/onlinepubs/009695399/functions/sem_wait.html and http://www.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_lock.html.
Richard Pennington
One significant difference (since I've seen people make this mistake before): 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.
ephemient
@ephemient, that would have made a great answer, very insightful
Matt Joiner
A: 

mutex is ued to avoid race condition between multiple threads.

whereas semaphore is used as synchronizing element used across multiple process.

mutex can't be replaced with binary semaphore since, one process waits for semaphore while other process releases semaphore. In case mutex both acquisition and release is handled by same.

C Learner
(-1) Incorrect generalization: for one, mutex's can be shared across processes -- for example: http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx. If your system doesn't have named mutex's just map some shared memory and create your own.
Hassan Syed
Not fair to flag it as "not useful". I have worked on M$ quite a bit. It is easy to tell someone to use shared memory. on M$, all kernel objects are named and shared. Mutex is a kernel object. A pthread mutex is a CRITICAL_SECTION in M$. There is no way to share CRITICAL_SECTION between processes!
hackworks