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.
private Mutex[] m_mutex;
private Thread[] m_threadIds;
private int m_threadLimit;
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.
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.
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.