semahore vs mutex

Posted on 2010-11-16
Medium Priority
Last Modified: 2012-05-10
i am trying to understand semaphores and mutex, just finished understand threads.

The example http://www.amparo.net/ce155/sem-ex.html 
uses semaphore to enter critical section to increment counter. The same thing can be easily implemented using mutex.

so what is the use case of semaphore. Is that just a different variation or is there something which semaphore can do whic mutex can't ?
Question by:learningunix
  • 3
  • 2
  • 2
  • +3
LVL 16

Accepted Solution

HooKooDooKu earned 336 total points
ID: 34149593
A Mutex is "All or Nothing".  Once a proces locks a Mutex, NOTHING else can gain access to it.

But a Semaphore has a resource count.  "Locking" a Semaphore decreases it's resource count by 1.  The Semaphore will only block a lock when the resource count is zero.

So a Semaphore that starts with a resource count of only 1 pretty much acts like a mutex.  But it has the flexability of starting with a higher "resource" count.
LVL 40

Assisted Solution

evilrix earned 332 total points
ID: 34149726
As HooKooDooKu eludes, a mutex is just a special case semaphore that has a maximum count of one to enforce Mutual Exclusion semantics.
LVL 33

Assisted Solution

phoffric earned 332 total points
ID: 34150558
More discussion on differences between mutex and semaphore here:

BTW - in some OS, there are different kinds of semaphores; for example, a semaphore type that can handle priority inversion.

A Binary Semaphore is permitted two values whose initial value is 1, which means it can be taken.

But you can implement a binary semaphore with reverse polarity, which means that no one can take it, since you initialize its value to 0. This type is typically used for signalling. The slave process (or thread) trys to take it, and is forced to wait. The master can signal the slave by releasing the semaphore (which increments it to 1). It is actually a counting semaphore, but its implementation makes it a reversed polarity binary semaphore, or just a signalling semaphore.
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 12

Expert Comment

ID: 34151177
Couple of more links from MSDN. The basic concept remains the same whether it be Unix/Windows


Author Comment

ID: 34151456
To summarize  ?

1. A mutex is nothing but a semaphore with max value 1:
2. Mutex can only be used within a single process but multiple threads.
3. Semaphores can be used within MULTIPLE process.

LVL 33

Expert Comment

ID: 34151488
>> A mutex is nothing but a semaphore with max value 1
A mutex is nothing but a semaphore with max value 1, and whose initial value is 1 (as opposed to a singalling semaphore whose initial value is 0.

>> Semaphores can be used within MULTIPLE process
yes, shared semaphores can be used within MULTIPLE process

>> Mutex can only be used within a single process but multiple threads
Maybe. But from my previous link:
"But, in general, I found some information that talks about shared mutex between processes. Look at discussion on PTHREAD_PROCESS_SHARED in these links":
LVL 40

Expert Comment

ID: 34152101
>> Semaphores can be used within MULTIPLE process

Nothing about a mutex or semaphore specifically makes them single or multi-process apart from naming them. Both are designed to be synchronisation objects in a single process for multiple threads. The *only* difference between them is a mutex has a fixed count of 1 and a semaphore can have any count you give it. A mutex only allows one thread into a "critical section" of code whereas a semaphore allows as many as is defined by the count.
LVL 12

Expert Comment

ID: 34154869
Mutex can only be used within a single process but multiple threads.

no. A named mutex can be used to synchronize threads across different processes. A critical section is limited to threads in a single process.
LVL 33

Expert Comment

ID: 34159799
In a mutex/semaphore question in  http://www.experts-exchange.com/OS/Unix/Q_26566229.html the authore said:
This link http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html states that  “Mutexes can be applied only to threads in a single process and do not work between processes as do semaphores”.

However, contrary to this statement, I found in http://linux.die.net/man/3/pthread_mutexattr_init:
"If an implementation supports the _POSIX_THREAD_PROCESS_SHARED option, then the process-shared attribute can be used to indicate that mutexes or condition variables may be accessed by threads of multiple processes."

Expert Comment

ID: 34159863
A mutex and a critical section both exclusively lock a resource. As noted by trinitrotoluene, a critical section can only be used within a proceess and a mutex can be used across processes.

Mutexes and semaphores can both be named in Windows. This means that you can open them by name without knowing their handle.  Critical sections can't be named.

Here's a very important difference between mutexes and semaphores. A mutex is reentrant. This means that if a particular thread locks it more than once, subsequent locks succeed. A semaphore is NOT reentrant. If a thread tries to lock a semaphore twice, it takes up two positions.

Semaphores can count up or down, depending on whether you want to have a maximum size. For example, a "push" operation on a fixed-size queue should block when the queue is full. A "pop" operation on a queue should block when the queue is empty. On the other hand, if you have a variable length queue, a push never needs to block. (But it DOES need to be protected with a mutex in order to update the data structures!)

Locking is a miserably complex subject. In the real world, low-level objects like mutexes and semaphores are often used to build more complex objects, such as a Single-Writer-Multiple-Reader lock.

Locking also causes the possibility of deadlock. There are rules that can be followed to prevent this, but it's not easy.

Locking can cause severe performance problems if it's not implemented properly. A mutex requires a switch to kernel mode to block. If you are doing this on a high-performace object, you will suddenly have a low-performance object.

If your head is spinning, get a copy of my book, "Multithreading Applications in Win32." You can buy a used one from Amazon for less than $5. You'll save yourself a lot of aggravation.

Finally, be aware that there are several fundamental differences between mutexes and semaphores on Windows versus Posix. If you do anything cross platform, make sure you understand the idiosyncracies of both.


Author Closing Comment

ID: 34242835

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question