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()
- {
-
- 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();
- }
-
- static void MutexDemo()
- {
- try
- {
-
- mutex.WaitOne();
- Console.WriteLine("{0} has entered in the Domain", Thread.CurrentThread.Name);
- Thread.Sleep(1000);
- Console.WriteLine("{0} is leaving the Domain\r\n", Thread.CurrentThread.Name);
- }
- finally
- {
-
- mutex.ReleaseMutex();
- }
- }
- }
- }
Example - Semaphore
- using System;
- using System.Threading;
- namespace threading
- {
- class Semaphore_Example
- {
-
-
-
-
-
- static Semaphore obj = new Semaphore(3, 2);
-
- static void Main(string[] args)
- {
- for (int i = 1; i <= 5; i++)
- {
- Thread t = new Thread(SempStart);
- t.Start(i);
- }
- Console.ReadKey();
- }
- static void SempStart(object id)
- {
-
- Console.WriteLine(id + " Wants to Get Enter for processing");
- try
- {
-
- obj.WaitOne();
- Console.WriteLine(" Success: " + id + " is in!");
- Thread.Sleep(5000);
- Console.WriteLine(id + "<<-- is exit because it completed there operation");
- }
- finally
- {
-
- obj.Release();
- }
- }
- }
- }
That's all. If you require any clarification about code, revert back with comments.