vote buttons
1
3
beginner
0
intermediate
0
advanced
06-Nov-2014 02:05 UTC
Rahul
100

1 Answers

vote buttons
2

Semaphores are used to prevent too many threads from accessing a resource. A good analogy I read in Albahari's book (C# in a nutshell) is to compare a semaphore with a bouncer in a nightclub. A nightclub has a certain capacity. The bouncer allows people to enter the nightclub till it is full. Once its full a queue builds up outside the nightclub and a person is allowed to enter only when some one else leaves the nightclub.

Semaphore is like the bouncer. A semaphore is created with a fixed capacity. Only a fixed amount of threads are allowed to access a resource determined by its capacity. Once its full all other threads have to wait till some threads leaves the resource.


class NightClub
{
  static SemaphoreSlim semaphore = new SemaphoreSlim (5);    
  static void Main()
  {
    for (int i = 1; i <= 10; i++) new Thread (EnterTheClub).Start (i);
  }
 
  static void EnterTheClub (object id)
  {
    Console.WriteLine (id + " queues up");
    semaphore .Wait();
    Console.WriteLine (id + " is in!");  
    Thread.Sleep (1000 * (int) id);    
    Console.WriteLine (id + " is leaving");
    semaphore.Release();
  }
}

Output

4 queues up
1 queues up
1 is in!
5 queues up
7 queues up
7 is in!
5 is in!
4 is in!
8 queues up
8 is in!
9 queues up
10 queues up
3 queues up
6 queues up
2 queues up
1 is leaving
9 is in!
4 is leaving
10 is in!
5 is leaving
3 is in!
7 is leaving
6 is in!
8 is leaving
2 is in!
3 is leaving
9 is leaving
2 is leaving
6 is leaving
10 is leaving
SemaphoreSlim and Semaphore are functionally similar. SemaphoreSlim is about 4 times faster than a Semaphore but SemaphoreSlim cannot be used for interprocess signalling.


06-Nov-2014 02:24 UTC
Rahul
100