1.

Show an example of how the Mutex synchronization mechanism works.

Answer»

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

using System;
using System.Collections;
using System.Threading;
namespace MutexDemo
{
class MutexDemoClass
{
private static Mutex mutex = new Mutex();
private const int countOfHits = 1;
private const int countOfThreads = 3;
private static void ThreadProcess()
{
for (int i = 0; i < countOfHits; i++)
{
showMutexDemo();
}
}

private static void showMutexDemo()
{
// Wait until it is safe to enter.
mutex.WaitOne();

Console.WriteLine("{0} has got the access of resource",
Thread.CurrentThread.Name);

// Code to access the resource mutually exclusively

// Wait until it is safe to enter.
Thread.Sleep(100);
Console.WriteLine("{0}'s access of the resource has been revoked",
Thread.CurrentThread.Name);
// Once the work is done, release the resource from Mutex
mutex.ReleaseMutex();
}

// Driver code
static void Main(string[] args)
{
for (int i = 0; i < countOfThreads; i++)
{
Thread thread = new Thread(new ThreadStart(ThreadProcess));
thread.Name = String.Format("Thread{0}", i + 1);
thread.Start();
}
}
}
}

The above code is a simple example to show how Mutex locks a resource and only that thread can release the Mutex.

Thread1 has got the access of resource
Thread1's access of the resource has been revoked
Thread2 has got the access of resource
Thread2's access of the resource has been revoked
Thread2 has got the access of resource
Thread3's access of the resource has been revoked


Discussion

No Comment Found