Semaphores

11 07 2011

A semaphore allows a special kind of critical region that is not mutually exclusive. Threads may perform a take or put operation on a semaphore, atomically decreasing or increasing its current count, respectively. When a thread tries to take from a semaphore that already has a count of 0, the thread blocks until the count becomes non-0. The initial count of the semaphore specifies the maximum number of threads that can be inside the region. Unlike mutexes, semaphores are never considered to be owned by a specific thread. Different threads can safely put and take from the semaphore without any problems.

To take from the semaphore a thread calls Wait() and to put a thread calls Release(). Semaphores are typically used to protect resources that are finite in capacity. A pool of database connections for example or a swimming pool with a maximum capacity. A semaphore can span processes in the same was as a Mutex if you give it a name on construction.

class SwimmingPool
{
  static SemaphoreSlim m_Sem = new SemaphoreSlim (2);

  static void Main()
  {
    for (int i = 1; i <= 5; i++) new Thread (Swim).Start (i);
  }

  static void Swim(object id)
  {
    Console.WriteLine (id + " wants to swim");
    m_Sem.Wait();
    Console.WriteLine (id + " is swimming");           // Only two swimmers
    Thread.Sleep (1000 * (int) id);                    // can be here at
    Console.WriteLine (id + " is done swimming");       // a time.
    m_Sem.Release();
  }
}
Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: