Junior — Middle
Explain what semaphores are and how they are used in thread management in programming.
sobes.tech AI
Answer from AI
Semaphore is a synchronization mechanism used to control access to shared resources in multithreaded applications. It contains a counter that indicates how many threads can access the resource simultaneously.
Main points:
- If the counter is greater than zero, a thread can enter and decrease the counter by 1.
- If the counter is zero, the thread is blocked and waits until another thread releases the resource.
- When a thread finishes working with the resource, it increases the counter, allowing other threads to continue.
Example in C# using SemaphoreSlim:
using System;
using System.Threading;
class Program
{
static SemaphoreSlim semaphore = new SemaphoreSlim(2); // maximum 2 threads at the same time
static void AccessResource(int id)
{
Console.WriteLine($"Thread {id} is waiting for access");
semaphore.Wait(); // request access
Console.WriteLine($"Thread {id} has gained access");
Thread.Sleep(1000); // simulate work with the resource
Console.WriteLine($"Thread {id} is releasing the resource");
semaphore.Release(); // release the resource
}
static void Main()
{
for (int i = 1; i <= 5; i++)
{
int threadId = i;
new Thread(() => AccessResource(threadId)).Start();
}
}
}
In this example, no more than two threads can work with the resource simultaneously; the rest wait for their turn.