Simple Semaphore example

Here is a very simple console application I wrote to demonstrate the use of Semaphores

using System;
using System.Threading;

namespace ConsoleApplication9
{
  class Program
  {
    /*
    * Creates a semaphore with 0 slots initially open, and specifies the maximum number
    * of slots is 10.
    */
    static Semaphore semaphore = new Semaphore(0, 10);

    static void Main(string[] args)
    {
      /* Release 5 slots. Until this is done no work can be performed because no slots
      * are allocated.
      */
      semaphore.Release(5);

      /*
      * Launch 10 new threads to see the semaphore in action.
      * Index is passed so we can see the threads executing seperately.
      */
      for (int i = 1; i < 11; i++)
      {
        Thread thread = new Thread(new ParameterizedThreadStart(Threaded));
        thread.Start(i);
      }

      //End of program
      Console.ReadKey();
    }

    //Threaded method called 10 times in main.
    static void Threaded(object state)
    {
      /* Wait indefinitely until a slot is available.
      * Add a very short timeout (ie 10 milleseconds) to see some waits
      * timeout.
      */
      if (semaphore.WaitOne())
      {
        try
        {
          //Short sleep to slow method execution down a little
          Thread.Sleep(10);
          //Write out the index
          Console.WriteLine((int)state);
        }
        finally
        {
          //Release a slot now we are finished.
          semaphore.Release();
        }
      }
      else
      {
        /* If you add a short timeout value to .WaitOne() some
        * waits will timeout.
        */
        Console.WriteLine("Semaphore timed out on " + (int)state);
      }
    }
  }
}

Tags: , ,

Leave a Reply