MUTEX - Thread Synchronization

Introduction

Mutex stands for Mutual Exclusion. It is a type of Thread Synchronization mechanism. Basically, it is an exclusive lock. It ensures that the blocks of code are executed only once at a time. It is applicable only on those resources which are being shared by multiple threads simultaneously.

The basic use of Mutex is inter-process synchronization because multiple applications can access the same Mutex object.
 
So, basically Mutex is used to serialize the access to a section of re-entrant code that can't be executed concurrently by more than one thread.  
 
Best real world example of Mutex
 
Let's say, Mutex is a key to a toilet. One guy can have the key and occupy the toilet at the time. When finished, the guy gives (frees) the key to the next guy in the queue.  
 
With a Mutex class, we basically call the WaitOne method to lock and release Mutex to unlock.
 
If you compare Mutex with Semaphore, then in depth, you would find that a Mutex is really a Semaphore with value 1.
 
A common use of a cross-process Mutex is to ensure that only one instance of a program is run at a time.
 
Below is the example of Mutex which will allow only one instance of program to run.
  1. public class MutexUtils  
  2.     {  
  3.         public static void OnlySingleInstance()  
  4.         {  
  5.             Mutex mutexObj = new Mutex(false"ProcessName");  
  6.   
  7.             try  
  8.             {  
  9.                 if (!mutexObj.WaitOne(TimeSpan.FromSeconds(10)))  
  10.                 {  
  11.                     Console.WriteLine("Exiting for now as another instance is in execution...");  
  12.   
  13.                     return;  
  14.                 }  
  15.             }  
  16.             catch (Exception ex)  
  17.             {  
  18.                 Console.WriteLine(ex);  
  19.             }  
  20.             finally  
  21.             {  
  22.                 mutexObj.ReleaseMutex();  
  23.             }  
  24.         }  
  25.     }  
Explanation

Suppose, one process "ProcessName" is already running and meanwhile user tries to start the process with the same name ProcessName process again. Then, Mutex will check the existing process name and current process name which are running. It will wait for 10 seconds and then close the other process by saying "Exiting for now as another instance is in execution..." 
 
Please find the attached zipped code for reference. 

Conclusion

Mutex is very powerful thread synchronization mechanism. It is very useful in case of inter-process Synchronization.
Ebook Download
View all
Learn
View all