Click here to Skip to main content
Click here to Skip to main content
Go to top

A simple in-process semaphore using C#

, 10 Jul 2003
Rate this:
Please Sign up or sign in to vote.
Creating a semaphore to limit a given number of threads accessing a resource in a process.

Introduction

Many times we are limited to use a controlled number of threads to access the resources at our disposal. This article describes how to create a semaphore (to be used inside a single process) and control the number of threads. If you want to use a global semaphore to control threads across processes, then you have to use Windows semaphores.

Semaphore code

The Semaphore.cs file contains the code which controls the threads and can be used by itself in any project. The constructor takes the number of threads to be controlled as the parameter and creates an array of mutexes which are used to block the threads. WaitHandle.WaitAny() is used to wait on this array of mutexes.

        // array of mutex to block the threads
        private Mutex[] m_mutex;

        // place holder to store thread to mutex mapping
        private Thread[] m_threadIds;

        // number of threads allowed to access the resources
        private int m_threadLimit;

        // contructor creates the mutexes
        public Semaphore(int threadLimit)
        {
            m_threadLimit = threadLimit;
            m_mutex = new Mutex[m_threadLimit];
            m_threadIds = new Thread[m_threadLimit];
            for (int i=0; i<m_threadLimit; i++)
            {
                m_mutex[i] = new Mutex();
                m_threadIds[i] = null;
            }
        }

It is important to map the current thread with the mutex it is blocking, it will be used to release the mutex when Semaphore.Release() is called on the semaphore. A simple Thread array is used to map the calling thread to the mutex locked by the thread, by calling Thread.CurrentThread in the code below.

        // if there is a timeout then WaitHandle.WaitTimeout is returned
        // calling thread should check for this
        public int Wait()
        {
            int index = WaitHandle.WaitAny(m_mutex);
            if (index != WaitHandle.WaitTimeout)
                m_threadIds[index] = Thread.CurrentThread;
            return index;
        }

When a release is called on the semaphore, the locking thread is searched in the array and ReleaseMutex() on the corresponding mutex is called to let the next thread.

        // release the mutex locked by the thread
        public void Release()
        {
            for (int i=0; i<m_threadLimits; i++)
            {
                if (m_threadIds[i] == Thread.CurrentThread)
                {
                    m_mutex[i].ReleaseMutex();
                    break;
                }
            }
        }

Testing the code

To test the semaphore code, a simple form is created with a button, it's purpose - to create a thread when pressed. A static instance of the semaphore is created to be shared by all the threads in the form.

       private static Semaphore m_semaphore = new Semaphore(5);

A static method is created which is used to kick off threads. The method waits on the semaphore. At any point, only the number of maximum threads mentioned will be allowed to pass beyond this point to display the message box.

        public static void TestThread()
        {
            m_semaphore.Wait();
            MessageBox.Show("I am on a new thread");
            m_semaphore.Release();
        }

The button click event is trapped and a new thread is created every time the button is pressed as shown below:

        private void StartThread_Click(object sender, System.EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(TestThread));
            t.Start();
        }

As we press the button, we can see that only 5 message boxes are shown, demonstrating that only 5 threads are allowed by the semaphore.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Sriram Chitturi
Architect
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberchait30116-Feb-14 12:45 
GeneralSemaphore class did not exist in 2003. PinmemberSriram Chitturi17-Feb-14 4:04 
GeneralRe: Semaphore class did not exist in 2003. Pinmemberchait30119-Feb-14 10:56 
Questionhmmm.... which ones better?? PinmemberJeff_____M___12-May-09 6:44 
AnswerRe: hmmm.... which ones better?? PinmemberChris@TCP29-May-10 10:46 
GeneralExcellent implementation of Semaphore PinmemberDriesens6-Jul-07 5:31 
GeneralPassing info to a thread Pinmemberpendarric26-Aug-03 16:11 
GeneralRe: Passing info to a thread Pinmemberzoltix9-Sep-03 22:21 
GeneralGood Job! Pinmemberfbougadou14-Jul-03 5:25 
GeneralThere are some problems with this implementation PinmemberBrian Gideon11-Jul-03 11:16 
Developing multithreaded applications is a very difficult task so I must commend you on trying.   However, there are some problems with this implementation of a semaphore.   It's actually ironic that the semaphore is very difficult to implement but contains very few lines of code.
 
The problem here is that the Wait and Release methods are not thread-safe.   There are many reasons for this.   Unfortunately, it's too difficult to explain in this message.   The problems can be easily demonstrated by placing an infinite while loop around what implementation is currently in the TestThread method in Form1.
 
Making the Wait and Release methods thread-safe is by no means an easy task.   The first thought might be to use the lock keyword around the implementations in both methods, but it's easy to see that this will quickly lead to a deadlock since a lock is acquired and held during the execution of the WaitHandle.WaitAny method.   Since the lock is held the Release method will never get a chance to release any mutexes and as a result the WaitHandle.WaitAny method will continue to block forever.
 
The second thought of placing the lock keyword after the WaitHandle.WaitAny line in the Wait method proves to be no better.   It actually allows the same race condition to occur if the lock wasn't even there in the first place!   Ick...how is this possibly fixed you ask?
 
Check out the implementation in the user samples area on www.gotdotnet.com.
 
Good luck,
Brian
 

GeneralRe: There are some problems with this implementation PinmemberDaniel Turini11-Jul-03 23:24 
GeneralRe: There are some problems with this implementation PinmemberSriram Chitturi12-Jul-03 7:04 
GeneralRe: There are some problems with this implementation PinmemberRahulGade19-Nov-04 21:23 
GeneralProblem in multithread PinmemberMember 918701115-Feb-13 22:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 11 Jul 2003
Article Copyright 2003 by Sriram Chitturi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid