Click here to Skip to main content
Click here to Skip to main content

Non-Kernel Semaphore

By , 31 May 2012
Rate this:
Please Sign up or sign in to vote.

Introduction

I've been using threads a long time in .NET and honestly the topic interests me very much. When I began to get deeper into multithreading I came to use other threading constructs rather than just the Monitor (lock) and Interlocked classes. Interlocked and volatile mechanisms are user mode constructs meaning that they do not transition into the kernel. Kernel level objects like Mutex and Semaphores are created and managed by the operating system and are system wide. If we use a semaphore in our application we must leave user mode and transition into kernel mode just to create it. There is a slight performance hit that we incur since the kernel does not trust us. While this hit is negligible it can begin to cost a lot when used in different types of scenarios.

Background

I like the functionality that the semaphore provides however in some cases I would like to use it in just one process and not transition into kernel mode and take a hit. I've decided to write a very simple non-kernel semaphore.

What it has:

  1. Fast creation time since it just a regular .NET non-kernel object.
  2. Only transitions to kernel mode when the maximum capacity has been met and more threads want to use it.

What it lacks:

  1. It's not system wide which makes sense because it 'mostly' stays in user mode.
  2. It does use Monitor which can transition into kernel mode, however this only occurs when all the slots have been filled.

The code

public class NonKernalSemaphore 
{
    private readonly object padlock = new object();
    private readonly int maxSlots;
    private int usedSlots;


    public NonKernalSemaphore(int maxSlots)
    {
        this.maxSlots = maxSlots;
    }

    public void Enter()
    {
        lock (padlock)
        {
            while (usedSlots == maxSlots)
            {
                Monitor.Wait(padlock);
            }

            usedSlots++;
        }
    }

    public void Release()
    {
        lock (padlock)
        {
            if (usedSlots > 0)
            {
                usedSlots--;
                Monitor.PulseAll(padlock);
            }
        }
    }
}

I wanted to keep this class as simple as possible without adding fluff so that I could cater for the basic usage scenario.

NonKernelSemaphore takes the maximum number of threads allowed at one time as constructor parameter maxSlots. It also keeps a count of how many threads are currently using the semaphore using the usedSlots field.

Enter Method Explanation

When a consumer calls the Enter() method a lock, padlock, is first acquired. We now check if there are any slots remaining in the semaphore. Obviously if usedSlots is equal to the maxSlots then all the slots are occupied. In this case we wait until another thread releases the slot by calling the Release() method. By calling Monitor.Wait() we transition into kernel mode and let the thread scheduler take care of things. Our scope at this point is still only process wide.

Release Method Explanation

Again in this method we must first call lock on the shared padlock object. We now decrease the usedSlots count which releases a slot in the semaphore. Then we awaken all the threads who are waiting on a slot by calling Monitor.PulseAll(). When the threads wake up they must first check if all the slots are used again hence the while condition (usedSlots == maxSlots).

Optimization

One optimization I was considering is only calling Monitor.PulseAll() only if there are threads waiting for an available slot. This is definitely better than blindly calling the method. In this case we just need to keep track of how much many threads are waiting by introducing a new variable, waitingThreads of type HashSet<int> and adding the id of any thread that is waiting. The Release() method will then check if there are threads waiting. If there is then call Monitor.PulseAll() otherwise just decrease usedSlots as usual. Here is the code:

public class NonKernalSemaphore 
{
    private readonly object padlock = new object();
    private readonly int maxSlots;
    private int usedSlots;
    private readonly HashSet<int> 
      waitingThreads = new HashSet<int>();

    public NonKernalSemaphore(int maxSlots)
    {
        this.maxSlots = maxSlots;
    }

    public void Enter()
    {
        lock (padlock)
        {
            while (usedSlots == maxSlots)
            {
                waitingThreads.Add(Thread.CurrentThread.ManagedThreadId);
                Monitor.Wait(padlock);
            }

            waitingThreads.Remove(Thread.CurrentThread.ManagedThreadId);
            usedSlots++;
        }
    }

    public void Release()
    {
        lock (padlock)
        {
            if (usedSlots > 0)
            {
                usedSlots--;

                if (waitingThreads.Count > 0)
                {
                    Monitor.PulseAll(padlock);
                }
            }
        }
    }
}

Feedbacks welcomed!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

FatCatProgrammer
Software Developer (Senior) Finance Industry
United States United States
Currently pursuing 'Programming Nirvana' (The ineffable ultimate in which one has attained disinterested wisdom and compassion as it relates to programming)
 
Acknowledgements:
 
Microsoft Certified Technologist for WPF and .Net 3.5 (MCTS)
Microsoft Certified Technologist for WCF and .Net 3.5 (MCTS)
Microsoft Certified Application Developer for .Net (MCAD)
Microsoft Certified Systems Engineer (MCSE)
Microsoft Certified Professional (MCP)
 
Sun Certified Developer for Java 2 Platform (SCD)
Sun Certified Programmer for Java 2 Platform (SCP)
Sun Certified Web Component Developer (SCWCD)
 
CompTIA A+ Certified Professional
 
Registered Business School Teacher for Computer Programming and Computer Applications (2004)
(University of the State of New York Education Department)
 
Graduated from University At Stony Brook

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 31 May 2012
Article Copyright 2012 by FatCatProgrammer
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid