What is Mutex in C#: Simple Explanation and Example
Mutex in C# is a synchronization tool that allows only one thread to access a resource at a time, preventing conflicts. It works like a lock that threads must wait to acquire before proceeding, ensuring safe access to shared data.How It Works
Imagine you have a single bathroom in a house shared by many people. Only one person can use it at a time to avoid confusion or accidents. A Mutex works the same way for computer programs: it lets only one thread use a resource at once.
When a thread wants to use a shared resource, it tries to 'lock' the Mutex. If no other thread has locked it, the thread gets access. If another thread already locked it, the new thread waits until the Mutex is released. This prevents two threads from changing the same data at the same time, which could cause errors.
Example
This example shows two threads trying to use a shared resource. The Mutex ensures only one thread runs the critical section at a time.
using System; using System.Threading; class Program { static Mutex mutex = new Mutex(); static void AccessResource(string threadName) { Console.WriteLine($"{threadName} is waiting to access the resource..."); mutex.WaitOne(); // Lock the mutex Console.WriteLine($"{threadName} has entered the critical section."); Thread.Sleep(1000); // Simulate work Console.WriteLine($"{threadName} is leaving the critical section."); mutex.ReleaseMutex(); // Release the mutex } static void Main() { Thread t1 = new Thread(() => AccessResource("Thread 1")); Thread t2 = new Thread(() => AccessResource("Thread 2")); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } }
When to Use
Use a Mutex when you have multiple threads or processes that need to use the same resource, like a file or shared data, but only one should access it at a time. This avoids problems like data corruption or crashes.
For example, if two parts of a program try to write to the same file simultaneously, a Mutex can make sure one finishes before the other starts. It's also useful in multi-process applications where different programs need to coordinate access.
Key Points
- Mutex allows only one thread or process to access a resource at a time.
- It works like a lock that threads must wait to acquire.
- Use it to prevent data conflicts and ensure safe access.
- It can be used across multiple processes, unlike some other locks.
- Always release the
Mutexafter use to avoid deadlocks.