In this blog, I am going to explain how to use Mutex and Semaphore in thread, for thread synchronization, with examples.
What is Mutex
Mutex works like a lock in C# for thread synchronization, but it works across multiple processes. Mutex provides safety against the external threads.
What is Semaphore?
Semaphore allows one or more threads to enter and execute their task with thread safety. Object of semaphore class takes two parameters. First parameter explains the number of processes for initial start and the second parameter is used to define the maximum number of processes which can be used for initial start. The second parameter must be equal or greater than the first parameter.
Example - Mutex
- using System;
- using System.Threading;
- namespace threading
- {
- class Mutex_Example
- {
- private static Mutex mutex = new Mutex();
- public void Example()
- {
- //Create mumber of thread to explain muiltiple thread example
- for (int i = 0; i < 4; i++)
- {
- Thread t = new Thread(MutexDemo);
- t.Name = string.Format("Thread {0} :", i + 1);
- t.Start();
- }
- }
- static void Main(string[] args)
- {
- Mutex_Example p = new Mutex_Example();
- p.Example();
- Console.ReadKey();
- }
- //Method to implement syncronization using Mutex
- static void MutexDemo()
- {
- try
- {
- //Blocks the current thread until the current WaitHandle receives a signal.
- mutex.WaitOne(); // Wait until it is safe to enter.
- Console.WriteLine("{0} has entered in the Domain", Thread.CurrentThread.Name);
- Thread.Sleep(1000); // Wait until it is safe to enter.
- Console.WriteLine("{0} is leaving the Domain\r\n", Thread.CurrentThread.Name);
- }
- finally
- {
- //ReleaseMutex unblock other threads that are trying to gain ownership of the mutex.
- mutex.ReleaseMutex();
- }
- }
- }
- }

Ali SufyanPosted Jul 1, 2021, 1:17 PM
As raised by Vamsee mudradi as well, You said second argument should be more tan first but you have initiated the semaphore with (3,2) , also if you could have discussed the output states, other than that its awesome read
Shiv Ratan KumarPosted Dec 12, 2019, 11:29 PM
Static Semaphore obj = new Semaphore(3, 2); it should be static Semaphore obj = new Semaphore(2, 3). The second parameter always must be equal or greater than the first parameter otherwise we will get an exception.
vamsee mudradiPosted Jul 29, 2019, 11:51 PM
You said second argument should be more tan first but you have initiated the semaphore with (3,2) which looks wrong.
kalu singh raoPosted Jul 27, 2016, 1:53 AM
Nice share