- class Program
- {
- static Semaphore _semaphore = new Semaphore(2, 2); // Allow 2 threads to access the resource simultaneously
- static int _counter = 0;
- static void Main()
- {
- for (int i = 0; i < 5; i++)
- {
- new Thread(IncrementCounter).Start();
- }
- Console.ReadKey();
- }
- static void IncrementCounter()
- {
- _semaphore.WaitOne();
- _counter++;
- Console.WriteLine($"Counter: {_counter}");
- _semaphore.Release();
- }
- }