Wednesday, September 28, 2011

What is Mutex? - Explanation and Animation

   
     In computer programming, a mutex (mutual exclusion object) is a program object that is created so that multiple program thread can take turns sharing the same resource, such as access to a file. Typically, when a program is started, it creates a mutex for a given resource at the beginning by requesting it from the system and the system returns a unique name or ID for it. After that, any thread needing the resource must use the mutex to lock the resource from other threads while it is using the resource. 
    If the mutex is already locked, a thread needing the resource is typically queued by the system and then given control when the mutex is locked during the new thread's use of the resource). becomes unlocked (when once more, the the mutex is locked during the new thread's use of the resource).
    Semaphore owns the resource ownership whereas mutex doesn't. Means when the semaphore enters the critical section by setting the sem_flag as one but because of some means(lets say dead lock) it gets blocked inside the critical section waiting for another resource,which is being used by another process/thread.So now no other process can enter the  critical section ...almost deadlock..means no other process can unset the sem_flag to zero..=> implies the process which sets the lock/flag has to unlock the flag.No other process/thread has the permission to unlock..


    On the other hand, mutex doesn't own the ownership means even if it gets blocked inside the crtitical region,any other process can enter the critical section. A semaphore post (or basically unlock) can be performed by  a different thread. However, in the case of mutex, it should be unlocked only by the same thread.

 Lets understand how does the Mutual Exclusion works using this animation -



0 comments:

Post a Comment