What is Semaphore and how to use that ?
Semaphore lets you set a limit on how many threads have access to a critical section ( A critical section is a piece of code that accesses a shared resource (data structure or device) but only limited number of threads can access it).
It's often described as a nightclub (the semaphore) where the visitors (threads) stands in a queue outside the nightclub waiting for someone to leave in order to gain entrance.
WaitOne() method when entering an area of code that you want restricted to a certain number of threads. When processing finishes, call the Release() method to release the slot back to the pool.
The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore. When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created.
There is no guaranteed order in which blocked threads enter the semaphore.
class Program { int result = 0; AutoResetEvent event1 = new AutoResetEvent(false); AutoResetEvent event2 = new AutoResetEvent(false); AutoResetEvent event3 = new AutoResetEvent(false); void Work1() { result = 1; event1.Set(); } void Work2() { result = 2; event2.Set(); } void Work3() { WaitHandle.WaitAll(new WaitHandle[] { event1, event2 }); result = 3; event3.Set(); } static void Main(string[] args) { Program a = new Program(); Thread worker1 = new Thread(a.Work1); Thread worker2 = new Thread(a.Work2); Thread worker3 = new Thread(a.Work3); worker3.Start(); worker1.Start(); worker2.Start(); WaitHandle.WaitAny(new WaitHandle[] { a.event3 }); Console.WriteLine(a.result); } }
class Program { static void Main(string[] args) { var semaphore = new SemaphoreTest(); semaphore.Start(); Console.ReadKey(); } }
And result says that threads were running in the batches (check seconds)
1.0007945 processing T1 1.0018164 processing T2 1.0018283 processing T3 2.0019704 processing T6 2.0019806 processing T5 2.0022565 processing T4 3.0023643 processing T8 3.0023743 processing T7 3.003351 processing T9 4.0027151 processing T1 4.0037565 processing T3 4.0037705 processing T2 Press any key to continue . . .