C Datastructures Networking OS

Wednesday 20 March 2013

DIFFERENCE BETWEEN SEMAPHORE AND MUTEX..

Mutex :
         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. Mutexes are typically used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread.

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

Here comes the question,
                    When to use mutex and when to use semaphore?
                    
The producer-consumer problem:

Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A producer thread will collect the data and writes it to the buffer. A consumer thread will process the collected data from the buffer. Objective is, both the threads should not run at the same time.


Using Mutex:

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.
At any point of time, only one thread can work with the entire buffer. The concept can be generalized using semaphore.


Using Semaphore:

A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.


There is misconception that binary semaphore and mutex are same.But they are not.The purpose of mutex and semaphore are different.Just the implementation is similar.

Mutex  is locking mechanism used to synchronize the access to resource.Only one task can acquire the lock.
Whereas Semaphore is a signaling mechanism.


No comments:

Post a Comment