Introduction
Thread Synchronization ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segments. It makes one thread wait, until it finishes other thread, when one thread already executes in the critical section. If proper synchronization techniques are not applied, it may cause race condition.
There are different ways to do thread synchronization. Locking is the famous way to to do thread synchronization. Basically, there are two kinds of locks - Exclusive and Non-Exclusive Lock.
A Non-Exclusive lock is a lock that notifies others that you are considering changing the file. When you have a file locked non-exclusively, others can modify the file. Thus, Semaphore comes under the category of Non-Exclusive Lock.
A Semaphore restricts the number of simultaneous users of the shared resources up to a maximum number. It ensures not more than a specific number of concurrent threads, which can access a resource.
A Semaphore is like a nightclub, it has a certain capacity, enforced by bouncer. Once it is full, no more people can enter and people wait outside in the form of queue. For each person that leaves, one people enters from the head of the queue into nightclub.
There are two functionalities- Semaphore and SemaphoreSlim. Semaphore incurs about 1 microseconds calling WaitOne or Release while SemaphoreSlim incurs about a quarter of it.
This is a basic example of Semaphore, where 5 threads are wanted to enter and execute but, I will restrict it up to 3 threads, using Semaphore.
- using System;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- namespace Semaphore
- {
- public class TheSempahore
- {
- static SemaphoreSlim sema = new SemaphoreSlim(3);
- public static void StartExecute()
- {
- for (int i = 1; i <= 5; i++)
- {
- new Thread(Enter).Start(i);
- }
- }
- private static void Enter(object id)
- {
- Console.WriteLine("{0} wants to enter", id);
- sema.Wait();
- Console.WriteLine("Id {0} is in!", id);
- Thread.Sleep(1000 * (int)id);
- Console.WriteLine("{0} is leaving", id);
- sema.Release();
- }
- }
- }
- Now, Call the method into entry point:
- class program
- {
- public static void main()
- {
- TheSempahore.StartExecute();
- Console.readkey();
- }
- }
Join the conversation! Your thoughts help the community grow.