Solved

semahore vs mutex

Posted on 2010-11-16
11
724 Views
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 ?
0
Comment
Question by:learningunix
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 16

Accepted Solution

by:
HooKooDooKu earned 84 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.
0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 83 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.
http://pheatt.emporia.edu/courses/2010/cs557f10/hand07/Mutex%20vs_%20Semaphore.htm
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 83 total points
ID: 34150558
More discussion on differences between mutex and semaphore here:
   http://www.experts-exchange.com/OS/Unix/Q_26566229.html

BTW - in some OS, there are different kinds of semaphores; for example, a semaphore type that can handle priority inversion.
    http://en.wikipedia.org/wiki/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.
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 12

Expert Comment

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

http://msdn.microsoft.com/en-us/library/ms684266%28v=VS.85%29.aspx
http://msdn.microsoft.com/en-us/library/ms685129%28v=VS.85%29.aspx
0
 

Author Comment

by:learningunix
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.

0
 
LVL 32

Expert Comment

by:phoffric
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":
   http://linux.die.net/man/3/pthread_mutexattr_init
   http://www.embedded-linux.co.uk/tutorial/mutex_mutandis
0
 
LVL 40

Expert Comment

by:evilrix
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.
0
 
LVL 12

Expert Comment

by:trinitrotoluene
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.
0
 
LVL 32

Expert Comment

by:phoffric
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."
   
0
 
LVL 7

Expert Comment

by:JimBeveridge
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.

0
 

Author Closing Comment

by:learningunix
ID: 34242835
thx
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

831 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