SemaphoreSlim semaphore = new SemaphoreSlim(3, 3); for (int i = 0; i < 3; i++) { Task.Run(() => { semaphore.Wait(); Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} accessing shared resource"); Thread.Sleep(2000); semaphore.Release(); Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} releasing shared resource"); }); }
Thread 4 accessing shared resource Thread 5 accessing shared resource Thread 6 accessing shared resource Thread 4 releasing shared resource Thread 6 releasing shared resource Thread 5 releasing shared resource
SemaphoreSlim semaphore = new SemaphoreSlim(2, 2); for (int i = 0; i < 5; i++) { Task.Run(() => { semaphore.Wait(); Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} accessing shared resource"); Thread.Sleep(2000); semaphore.Release(); Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} releasing shared resource"); }); }
Thread 4 accessing shared resource Thread 5 accessing shared resource Thread 4 releasing shared resource Thread 6 accessing shared resource Thread 5 releasing shared resource Thread 6 releasing shared resource Thread 7 accessing shared resource Thread 8 accessing shared resource Thread 7 releasing shared resource Thread 8 releasing shared resource