How to protect shared resources and serialize the processing using Mutex and Semaphore.
This set shows some ways of doing thread synchronization in C#.
Mutex also helps us to ensure that our code is thread-safe. That means when we run our code in a multi-threaded environment then we don’t end up with inconsistent results.
public static class MutexSample
{
public static void Exeute()
{
for (int i = 0; i < 5; i++)
{
Thread doWorkThread = new Thread(new ParameterizedThreadStart(doWork));
doWorkThread.Start(i);
}
Console.ReadLine();
}
//Mutex(mutual exclusion) is very similar to lock/Monitor. The difference is that it can work across multiple processes.
//Make mutex.
private static Mutex mutex = new Mutex();
private static void doWork(object threadNumber)
{
try
{
//The code will stop executing here and wait until the lock is released by the previous thread.
mutex.WaitOne();
Console.WriteLine("Thread " + threadNumber.ToString() + " has started.");
//Simulate doing time consuming work.
Thread.Sleep(1500);
Console.WriteLine("Thread " + threadNumber.ToString() + " is done.");
}
finally
{
//Realesase the lock so other threads can now get access.
mutex.ReleaseMutex();
}
}
}
Semaphore is mainly used in scenarios where we have a limited number of resources and we have to limit the number of threads that can use it. The semaphore class lets you limit the number of threads accessing a critical section.
Semaphores are Int32 variables stored in an operating system's resources. When we initialize the semaphore object, we initialize it with a number. This number limits the threads that can enter the critical section.
For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object.
public static class SemaphoreSample
{
public static void Execute()
{
for (int i = 0; i < 5; i++)
{
Thread doWorkThread = new Thread(new ParameterizedThreadStart(doWork));
doWorkThread.Start(i);
}
Console.ReadLine();
}
//A semaphore is very similar to lock/Monitor. The difference is that it can allow for a specified amount of threads to work with the same resources at the same time.
//Make a semaphore that allows for up to two threads to work with the same resource.
private static Semaphore semaphore = new Semaphore(1, 1); //Semaphore(initial thread count, max thread count)
private static void doWork(object threadNumber)
{
try
{
//The code will stop executing here and wait until the lock is released by the previous thread.
semaphore.WaitOne();
Console.WriteLine("Thread " + threadNumber.ToString() + " has started.");
//Simulate doing time consuming work.
Thread.Sleep(1500);
Console.WriteLine("Thread " + threadNumber.ToString() + " is done.");
}
finally
{
//Realesase the lock so other threads can now get access.
semaphore.Release();
}
}
}
Information about Mutex
Information about Semaphore