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
Comments(10)
margueritewt5
11/29/2024 8:33:11 AMyvetteqr2
11/28/2024 9:24:35 AMmarahh9
11/27/2024 6:39:40 PMshaneyf2
11/27/2024 12:11:06 PMsoniang4
11/27/2024 1:57:41 AMclaudiadf9
11/26/2024 7:31:06 AMpatricekx11
11/25/2024 11:35:11 PMmarvined7
11/25/2024 2:53:22 AMluishh2
11/18/2024 8:10:56 AMericqg60
11/18/2024 5:41:58 AM