Tuesday, December 19, 2006

The Mutex (C# - Threading)

Mutex is used to set exclusive access on shared resources in multi-thread programs. This means only one thread can access shared object at a time. A mutex is a perfect synchronization mechanism in C# threading.

Consider a example of when two threads accessing same system resources like files, system registry, Environment variables, etc. And you want to put exclusive access in multithreaded environment on shared resources then this can be achieved using mutex.

System.Thread.Mutex Class:

Above class supports Mutex.

To acquire Mutex call WaitOne()

To release Mutex call ReleaseMutex()

Example:

using System.Threading;

Mutex objMutex = new Mutex();

//Some code goes here

objMutex.WaitOne(); //Acquire

//Code to get exclusive access

//.....

objMutex.ReleaseMutex(); //Release

Mutex Code Snippet:

using System.Threading;

class FileAccess

{

public static Mutex mtx = new Mutex(); //Mutex variable

//Method to read/write in File

}

class FirstThread

{

public Thread t1;

//Uses above class method to R/W file

FirstThread()

{

t1= new Thread(this.CallFileWrite);

t1.Start();

}

void CallFileWrite()

{

FileAccess.mtx.WaitOne();

Console.WriteLine(“t1: In Mutex ”);

//File writing code ......

Console.WriteLine(“t1: Out Mutex ”);

FileAccess.mtx.ReleaseMutex();

}

}

}

class SecondThread

{

public Thread t2;

//Uses above class method to R/W file

SecondThread()

{

t2= New Thread(this.CallFileWrite);

t2.Start();

}

void CallFileWrite()

{

FileAccess.mtx.WaitOne();

Console.WriteLine(“t2: In Mutex ”);

//File writing code ...... for same file in t1 thread

Console.WriteLine(“t2: Out Mutex ”);

FileAccess.mtx.ReleaseMutex();

}

}

class MutexExample

{

void main()

{

FirstThread mFt1 = new FirstThread();

SecondThread mSt2 = new SecondThread();

MFt1.t1.Join();

MSt2.t2.Join();

}

}

3 comments:

Anonymous said...

Helpful information.
Thanks.

yankeeno1 said...

was a good help for starters like me !!!!

Anonymous said...

Thank you... It's very helpful

Visitor Count: