Tuesday, April 28, 2009

Mutex and Semaphore

The source are blocked between the part of WaitOne() and MutexRelease(). The difference between Mutex and Monitor/Block is a Mutex allows synchronization across AppDomain and process boundaries and is flexible.

Here is an example to use Mutex. If one Console application is still running on the Read() method. When we start a new application, it will write out " another instance of this application already owns...".

using System;
using System.Threading;

static void Main(string[] args)
{
bool ownsMutex;
using (Mutex m = new Mutex(true, "MYMUTEX", out ownsMutex))
//pay attention to the "using" usage here
{
if (ownsMutex)
{
m.WaitOne(1000);
Console.WriteLine("Owned");
Console.Read();
m.ReleaseMutex();
}
else
{
Console.WriteLine("Another instance of this application " +
" already owns the mutex named MutexExample.");
}

/* Notice this is also often written styl:
if (! ownsMutex)
{
Console.WriteLine("Already running");
Console.ReadLine();
return; //exit the application
}
Console.WriteLine("First instance");
// do you app stuff here
// e.g. Application.Run(new Form1());
Console.ReadLine();
ownsMutex.Close();
*/
}

The msdn has an example of guarentee the resources be used by one thread a time:
using System;
using System.Threading;

class Test
{
// Create a new Mutex. The creating thread does not own the
// Mutex.
private static Mutex mut = new Mutex();
private const int numIterations = 1;
private const int numThreads = 3;

static void Main()
{
// Create the threads that will use the protected resource.
for(int i = 0; i < numThreads; i++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
myThread.Start();
}

// The main thread exits, but the application continues to
// run until all foreground threads have exited.
}

private static void MyThreadProc()
{
for(int i = 0; i < numIterations; i++)
{
UseResource();
}
}

The Semaphore class is used to throttle usage of some resources. Mutex like a key of a door, when a person use the key and enter a room, when he leaves the room, he give the key to the other person, while Semaphore like a room with some limitation of size.So Mutex is a special Semaphore with capacity 1.

Semaphore theSemaphore=new Semaphore(0,10);
//first parameter is initial counts, and the sencond is the capacity.
When we release the slot, we can use:
theSemaphore.Release(5);

Both Mutex and Semaphore has static method of OpenExisting("Name") to Open an existing Mutex or Semephore.

No comments: