using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace SemaphoreExample { class SharedResource { public bool Used { get; set; } public object ResObject { get; set; } } class Program { static SharedResource[] resources; static Semaphore sem; static SharedResource GetResource() { sem.WaitOne(); SharedResource res = resources.First(x => !x.Used); res.Used = true; Console.WriteLine("Thread {0} was granted a resource", Thread.CurrentThread.Name); return res; } static void FreeResource(SharedResource res) { if (res.Used) { res.Used = false; int i = sem.Release(); Console.WriteLine("Thread {0} freed a resource, {1} resources was free", Thread.CurrentThread.Name, i); } } static void DoWork() { while (true) { SharedResource res = GetResource(); Thread.Sleep(1000); FreeResource(res); Thread.Sleep(1000); } } static void Main(string[] args) { resources = new SharedResource[3] { new SharedResource(), new SharedResource(), new SharedResource() }; sem = new Semaphore(3,3); for (int i =1; i <=6; i++) { Thread p = new Thread(DoWork); p.Name = i.ToString(); p.Start(); Thread.Sleep(100); } } } }