Threading Simplified: Part Twelve (Mutex)

I am again here to continue the discussion around Threading. Today we will discuss about Mutex and related concepts. Before starting, let us visit the previous articles of the series,

Let’s start by putting some questions to understand the concepts.

What is Mutex in Multithreading and how is it different to lock?

Mutex stands for Mutual Exclusion and can be used for inter-process synchronization. Mutex works similarly to lock except that it’s an operating system level lock and hence can be used to lock across processes. On the contrary lock only works across threads in an AppDpmain of a process.

Mutex object can also be passed as a method parameter unlike lock.

Why Mutex is required?

Mutex can be used in cases when we want to make sure that any piece of code if locked, should not be accessed across processes. We can also use Mutex to check if another instance of the application using the same Mutex is running or not.

What is unnamed and named Mutex?

Unnamed mutex is a mutex when you don’t specify its name while creation. Unnamed mutex works across App Domains in a process.

Whereas named mutex has a bigger scope and it works across processes in an operating system.

Does lock and unnamed Mutex have similar locking scope?

No. Lock works across threads in an App Domain whereas unnamed mutex works across App domains in a process.

How to use Mutex in an application?

Mutex can be activated by WaitOne method and can be released by ReleaseMutex.

Another way to release Mutex is to close or release the mutex variable.

Similar to lock, Mutex can be released only by the thread which has activated it and not by any other running threads.

Let’s understand this by simple example.

Let’s first see an example by which we can determine that another instance of the program is running or not.

To test this, execute the below code in two different projects one after another, the later one should print “Already running”. The reason is first instance will create Mutex of name “ThreadingDemo” and hence it won’t allow another instance or process to create the same Mutex as it’s already present.

It also demonstrates that Mutex works cross processes.
  1. static void Main(string[] args)  
  2.         {  
  3.               
  4.             Console.Title = "Mutex Demo";  
  5.   
  6.             bool createdNew;  
  7.             using (Mutex m = new Mutex(false"ThreadingDemo"out createdNew))  
  8.             {  
  9.                 if (createdNew)  
  10.                 {                      
  11.                     Console.WriteLine("Not running");  
  12.                 }  
  13.                 else  
  14.                 {  
  15.                     Console.WriteLine("Already running");  
  16.                 }  
  17.             }  
  18.         }  
There is one more way to check if another instance of program (holding the same Mutex) is running or not using OpenExisting method.
  1. static bool IsSingleInstanceExists()  
  2.         {  
  3.             try  
  4.             {  
  5.                 // Try to open existing mutex.  
  6.                 Mutex.OpenExisting("ThreadingDemo");  
  7.             }  
  8.             catch  
  9.             {  
  10.                 // If exception occurred, there is no such mutex present.  
  11.                 Mutex m = new Mutex(true"ThreadingDemo");                  
  12.                 return true;  
  13.             }  
  14.             // More than one instances are present.  
  15.             return false;  
  16.         }  
  17.   
  18. static void Main(string[] args)  
  19.         {  
  20.             Console.Title = "Mutex Demo";  
  21.             Console.WriteLine("Is only instance running: {0}", IsSingleInstanceExists());  
  22.         }  
To Test, either execute the same code in two different projects or compile the project and open two instances of executable file. You should get output as follows.

demo

demo

So far, we discussed what Mutex is and how it’s different from lock and how to check if another instance holding the same Mutex is running or not. Now let’s see how to use it.
  1. private static readonly Mutex mutex = new Mutex();  
  2.         static Thread thread1 = new Thread(DoWork);  
  3.         static Thread thread2 = new Thread(DoWork);  
  4.         public static void DoWork()  
  5.         {  
  6.             mutex.WaitOne();  
  7.             try  
  8.             {  
  9.                 Console.WriteLine("{0} has entered", thread1.Name);  
  10.                 //Safe Code  
  11.                 Thread.Sleep(2000);  
  12.                 Console.WriteLine("{0} has exited", thread2.Name);  
  13.             }  
  14.             finally  
  15.             {  
  16.                 mutex.ReleaseMutex();  
  17.             }  
  18.         }  
  19.   
  20. static void Main(string[] args)  
  21.         {  
  22.             Console.Title = "Mutex Demo";  
  23.             thread1.Name = "Thread1";  
  24.             thread1.Start();  
  25.             thread2.Name = "Thread2";  
  26.             thread2.Start();  
  27.          }  
Output:

output

As you can see that how Thread1 and Thread2 has entered and exited from Mutex.

Hope you have liked the article. Look forward for your comments/suggestions.

Read more articles on Threading:


Similar Articles