Threading with Mutex

A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wide as well as application-wide.

A Mutex is a synchronization primitive that can also be used for interprocess synchronization. When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a Mutex, the second thread that wants to acquire that Mutex is suspended until the first thread releases the Mutex.

In short, A mutual exclusion ("Mutex") is a mechanism that acts as a flag to prevent two threads from performing one or more actions simultaneously. The entire action that you want to run exclusively is called a critical section or protected section.

A critical section is a piece of code that accesses a shared resource (data structure or device) but the condition is that only one thread can enter in this section at a time.

Modern programming languages support this natively. In C#, it's as simple as:

  • Instantiating a new static Mutex object that's accessible from each thread.
  • Wrapping whatever code you want to be executed in the critical section with that object's WaitOne() and ReleaseMutex() methods in each thread

With a Mutex class, you call the WaitHandle.WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing a Mutex automatically releases it. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it.

This example shows how a local Mutex object is used to synchronize access to a protected resource.

  1. using System;  
  2. using System.Collections;  
  3. using System.Threading;  
  4. namespace Mutexclass  
  5. {  
  6. class Akshay  
  7.     {  
  8.         private static Mutex mutex = new Mutex();  
  9.         private const int numhits = 1;  
  10.         private const int numThreads = 4;  
  11.         private static void ThreadProcess()  
  12.         {  
  13.             for (int i = 0; i < numhits; i++)  
  14.             {  
  15.                 UseCsharpcorner();  
  16.             }  
  17.         }  
  18.         private static void UseCsharpcorner()  
  19.         {  
  20.             mutex.WaitOne();   // Wait until it is safe to enter.  
  21.             Console.WriteLine("{0} has entered in the C_sharpcorner.com",  
  22.                 Thread.CurrentThread.Name);  
  23.             // Place code to access non-reentrant resources here.  
  24.            Thread.Sleep(500);    // Wait until it is safe to enter.  
  25.             Console.WriteLine("{0} is leaving the C_sharpcorner.com\r\n",  
  26.                 Thread.CurrentThread.Name);  
  27.             mutex.ReleaseMutex();    // Release the Mutex.  
  28.         }  
  29.        static void Main(string[] args)  
  30.        {  
  31.              for (int i = 0; i < numThreads; i++)  
  32.             {  
  33.                 Thread mycorner = new Thread(new ThreadStart(ThreadProcess));  
  34.                 mycorner.Name = String.Format("Thread{0}", i + 1);  
  35.                 mycorner.Start();  
  36.             }  
  37.             Console.Read();  
  38.         }  
  39.     }  
  40. }  
Output

shres.gif

Use a Mutex to control a shared resource against two current threads

  1. using System;  
  2. using System.Threading;  
  3. class MyCounter  
  4. {  
  5.     public static int count = 0;  
  6.     public static Mutex MuTexLock = new Mutex();  
  7. }  
  8. class IncThread  
  9. {  
  10.     public Thread th;  
  11.     public IncThread()  
  12.     {  
  13.         th = new Thread(this.GO);  
  14.         th.Start();  
  15.     }  
  16.     void Go()  
  17.     {  
  18.         Console.WriteLine("IncThread is waiting for the mutex.");  
  19.         MyCounter.MuTexLock.WaitOne();  
  20.         Console.WriteLine("IncThread acquires the mutex.");  
  21.         int num = 10;  
  22.         do  
  23.         {  
  24.             Thread.Sleep(50);  
  25.             MyCounter.count++;  
  26.             Console.WriteLine("In IncThread, MyCounter.count is " + MyCounter.count);  
  27.             num--;  
  28.         } while (num > 0);  
  29.         Console.WriteLine("IncThread releases the mutex.");  
  30.         MyCounter.MuTexLock.ReleaseMutex();  
  31.     }  
  32. }  
  33. class DecThread  
  34. {  
  35.     public Thread th;  
  36.     public DecThread()  
  37.     {  
  38.         th = new Thread(new ThreadStart(this.Go));  
  39.         th.Start();  
  40.     }|  
  41.    void Go()  
  42. |    {  
  43.         Console.WriteLine("DecThread is waiting for the mutex.");  
  44.         MyCounter.MuTexLock.WaitOne();  
  45.         Console.WriteLine("DecThread acquires the mutex.");  
  46.         int num = 10;  
  47.         do  
  48.         {  
  49.             Thread.Sleep(50);  
  50.             MyCounter.count--;  
  51.             Console.WriteLine("In DecThread, MyCounter.count is " + MyCounter.count);  
  52.             num--;  
  53.         } while (num > 0);  
  54.         Console.WriteLine("DecThread releases the mutex.");  
  55.         MyCounter.MuTexLock.ReleaseMutex();  
  56.     }  
  57. }  
  58. class MainClass  
  59. {  
  60.     public static void Main()  
  61.     {|  
  62.         IncThread myt1 = new IncThread();  
  63.         DecThread myt2 = new DecThread();  
  64.         myt1.thrd.Join();  
  65.         myt2.thrd.Join();  
  66.         Console.Read();  
  67.     }  
  68. }  
Output

2.gif

Use the Mutex object: WaitOne

An overloaded WaitOne() method also accepts a TimeSpan object, useful if the thread should wait only until a period of time has lapsed. Typically this is employed when there's a risk ofdeadlock, where two or more threads are waiting for the same Mutex to become available simultaneously. Deadlock is as bad as it sounds, since it can result in an application that has "stalled out" for all intents and purposes.

  1. using System;  
  2. using System.Threading;  
  3. namespace waitonmethod  
  4. {  
  5. class Akshay  
  6.     {  
  7.         private static int Runs = 0;  
  8.         static Mutex mutex = new Mutex(false"RunsMutex");|  
  9.         public static void CountUp()  
  10.         {  
  11.             while (Runs < 10)  
  12.             {  
  13.                 // acquire the mutex  
  14.                 mutex.WaitOne();  
  15.                 int Temp = Runs;  
  16.                 Temp++;  
  17.                 Console.WriteLine(Thread.CurrentThread.Name + " " + Temp);  
  18.                 Thread.Sleep(800);  
  19.                 Runs = Temp;  
  20.                 // release the mutex  
  21.                 mutex.ReleaseMutex();  
  22.             }  
  23.         }  
  24.         public static void Main()  
  25.         {  
  26.             Thread t2 = new Thread(new ThreadStart(CountUp));  
  27.             t2.Name = "t2";  
  28.             Thread t3 = new Thread(new ThreadStart(CountUp));  
  29.             t3.Name = "t3";  
  30.             t2.Start();  
  31.             t3.Start();  
  32.             Console.Read();  
  33.         }  
  34.     }  
  35. }  
Output

3.gif

Own a Mutex

A Mutex object can be owned by a thread. When owned, it can only be owned by one single thread. When it is owned by a thread, other threads cannot own it until the original thread owner releases it. A thread which wants to own a Mutex calls the Mutex instance's WaitOne() method. An owning thread which wants to release the Mutex calls the ReleaseMutex() method.

  1. using System;  
  2. using System.Threading;  
  3. namespace ownamutex  
  4. {  
  5.  class Akshay  
  6.     {  
  7.         public static void Main()  
  8.         {  
  9.            bool ownsMutex;  
  10.              using (Mutex mutex = new Mutex(true"MutexExample"out ownsMutex))  
  11.             {  
  12.                 if (ownsMutex)  
  13.                 {  
  14.                     Console.WriteLine("Owned");  
  15.                     mutex.ReleaseMutex();  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                    Console.WriteLine("Another instance of this application " +" already owns the mutex named MutexExample.");  
  20.                 }  
  21.             }  
  22.             Console.Read();  
  23.         }  
  24.     }  
  25. }  
Output

4.gif

Name a Mutex

A Mutex can be either named or unnamed. If a Mutex is named, it is eligible to be a system-wide Mutex that can be accessed from multiple processes. If a Mutex is unnamed, it is an anonymous Mutex which can only be accessed within the process in which it is created.

  1. using System;  
  2. using System.Threading;  
  3. namespace Namingthread  
  4. {  
  5.     class Akshay  
  6.     {   
  7.         public static void Main(string[] args)  
  8.         {  
  9.             string mutexName = "akshay";  
  10.             Mutex m = new Mutex(false, mutexName);  
  11.             for (; ; )  
  12.             {  
  13.                 m.WaitOne();  
  14.                 Console.WriteLine("Have Mutex");  
  15.                 Console.WriteLine("Releasing");  
  16.                 m.ReleaseMutex();  
  17.             }  
  18.             Console.Read();  
  19.         }  
  20.    }  
  21. }  
Output

5.gif


Similar Articles