#Mutex :Kernel level Synchronization Mechanism

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 :

Capture.PNG

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. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s