Link to home
Start Free TrialLog in
Avatar of thanesh
thanesh

asked on

Using Mutex Vs Semaphore

Hi Experts,

I need to protect some data in a multi-threading/multi-processing enviorment.  What syncronization
mechanism should I use.  What is the difference in using Semaphore vs mutexes.  
Avatar of jkr
jkr
Flag of Germany image

The difference between mutexes and semaphores basically is that a mutex only grants access to the secured resource exclusively for *one* thread/instance/request, whereas a semaphore has a pin count that would allow multiple threads/instances/requests.
hi thanesh,

have a look at this:

http://koti.mbnet.fi/niclasw/MutexSemaphore.html


hope it helps :)
ike
Avatar of thanesh
thanesh

ASKER

Thanks guys, I remember reading somewhere that a mutex only protects within multi-threads and semaphore can be used across different processes.  Is it right?  
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Jkr,

//  No, both can be used across process boundaries. Only CRITICAL_SECTIONs are limited to a single process.

But Mutexes are used to protect critical section, so I see some conflict in the statement above.

Please correct me if I'm wrong ?

B.T

Hi jkr,

If you mean critical section objects that are used to synchronize threads , I understand your point.

Please forget my above posting.

B.T
If you are in a UN*X environment and therefore don't grok CRITICAL_SECTIONs, and you are using pthreads library (i.e. light weight processes), you are working within the user space, which doesn't cross into other processes.

If you are using System V IPC, your semaphore objects (sem_get etc) are in the kernel space and these can be seen by multiple processes.
Mutex allow only one person at a time to enter CRITICAL_SECTIONs but a  semaphore restricts the number of simultaneous users of a shared resource up to a maximum number.
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

A semaphore allows more than one thread to enter CRITICAL_SECTIONs up to MAX, and push remaining threads to queue.