Advertisement
ivorakitin

Semaphores

Apr 9th, 2025 (edited)
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ConsoleApp23
  9. {
  10.     class Program
  11.     {
  12.         public static Semaphore semaphore = new Semaphore(3, 5);
  13.         public static void Main(string[] args)
  14.         {
  15.             for (int i = 0; i < 10; i++)
  16.             {
  17.                 Thread threadObject = new Thread(Process);
  18.                 threadObject.Name = "Thread: " + i;
  19.                 threadObject.Start();
  20.             }
  21.             Console.ReadLine();
  22.         }
  23.         private static void Process()
  24.         {
  25.             Console.WriteLine("{0} is waiting to enter the critical section.", Thread.CurrentThread.Name);
  26.             semaphore.WaitOne();
  27.             Console.WriteLine("{0} is inside the critical section now...", Thread.CurrentThread.Name);
  28.             Thread.Sleep(1000);
  29.             Console.WriteLine("{0} is releasing the critical section...", Thread.CurrentThread.Name);
  30.             semaphore.Release();
  31.         }
  32.     }
  33. }
  34.  
Tags: semaphores
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement