Successfully added
How to Implement Thread Synchronization using Semaphore
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();
}
}
}
Semaphore
Leave a Comment
All fields are required. Your email address will not be published.
Comments(10)
luishh2
11/18/2024 8:10:56 AMericqg60
11/18/2024 5:41:58 AMyolandato4
11/16/2024 11:46:23 PMlouellanf6
11/16/2024 4:04:12 PMnatashayn6
11/15/2024 1:49:22 AMceciljb11
11/14/2024 8:38:39 PMveronicaia6
11/14/2024 5:38:25 AMshawnajc10
11/14/2024 3:11:03 AMlesliesr11
11/12/2024 11:26:05 PMcelinaos18
11/12/2024 7:09:46 PM