Mutex ensures only one thread can enter particular section. Mutex is similar to lock statement the only difference is that Mutex can work across multiple processes while lock can work only for multiple threads. Mutex ensures only one process (application) can run at a time. Mutex is slower than lock. We can use WaitOne method to acquire lock and ReleaseMutex to release lock.
There are two types of mutex available, named and unnamed.
Unnamed mutex are called as local mutex and available within your process.
Only threads inside your process can access it. While named mutex are visible throughout
the operating system and multiple processes can be able to access it. Checkout Mutex
page on MSDN for more information.
Let’s understand with simple example.
public static Mutex
mutex = new Mutex();
public static void DoWork()
{
mutex.WaitOne();
Console.WriteLine("Thread {0} has entered",
Thread.CurrentThread.Name);
Thread.Sleep(2000);
Console.WriteLine("Thread {0} is leaving",
Thread.CurrentThread.Name);
mutex.ReleaseMutex();
}
public static void Main()
{
for (int i = 0; i < 3; i++)
{
Thread t1 = new Thread(new ThreadStart(DoWork));
t1.Name = "Thread " +
i.ToString();
t1.Start();
}
}
As demonstrated in above code, WaitOne method requests to
acquire a lock and ReleaseMutex method request to release lock. Mutex can only
be released by the thread that acquired it. The main method creates three
threads one by one and tries to access DoWork method. DoWork method implements
mutex so only one thread at a time will able to access.
No comments:
Post a Comment