Advertisement
ivandrofly

C# - Semaphore

Feb 17th, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.74 KB | None | 0 0
  1. using System.Threading;
  2.  
  3. namespace Semaphore_Demo
  4. {
  5.     class Program
  6.     {
  7.         static Semaphore semaphore = new Semaphore(3, 3);
  8.  
  9.         static void Main(string[] args)
  10.         {
  11.             for (int i = 0; i < 20; i++)
  12.             {
  13.                 new Thread(DoSomething).Start(i);
  14.             }
  15.             Console.Read();
  16.         }
  17.         static void DoSomething(object id)
  18.         {
  19.             Console.WriteLine(id + " wants to access the semaphore");
  20.             semaphore.WaitOne();
  21.             Console.WriteLine(id + " as successed to access the semaphore");
  22.             Thread.Sleep(2000);
  23.             Console.WriteLine(id + " is about to leave the smeaphore");
  24.             semaphore.Release();
  25.         }
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement