Mutex Uses :
1.used when we need deadlock free Multiple Lock Acquisition. Mutex implemented with help of WaitHandle.
2.Single Instance of Application Instance.
Dead Lock free Multiple Lock Acquisition :
A sample Deadlock Code :
class Deadlock { static object a = new object(); static object b =new object(); public static void lock1() { lock (a) { Thread.Sleep(1000); Console.WriteLine("Waiting for Resource B"); lock (b) { Console.WriteLine("Accquired Resouce B"); } } } public static void lock2() { lock (b) { Thread.Sleep(1000); Console.WriteLine("Waiting for Resource A"); lock (a) { Console.WriteLine("Accquired Resouce A"); } } } public static void CreateThreads() { var thread = new Thread[2]; thread[0] = new Thread(lock1); thread[1] = new Thread(lock2); thread[0].Start(); thread[1].Start(); } }
Mutex and WaitHandle :
We could use WaitHandle Method WaitHandle.WaitAll() which takes parameter as an array of mutex(mutex inherits from waithandle) which would return true or false based on resource availability.