SemaphoreSlim and Mutex

A lock admits one thread; a semaphore admits a number of them. SemaphoreSlim is the in-process counter that a task waits on asynchronously, and Mutex is the operating-system object that can also be seen by another process. Both count permits: a thread takes one, works, and gives it back.

A limit on concurrency

Five tasks want to run, and the program allows two at a time. The counter of the tasks that are inside is guarded by a lock, so the maximum is a measured number and not a guess:

var semaphore = new SemaphoreSlim(2); var gate = new object(); var running = 0; var max = 0; var completed = 0; var tasks = Enumerable.Range(1, 5).Select(async id => { await semaphore.WaitAsync(); try { lock (gate) { running++; max = Math.Max(max, running); } await Task.Delay(10); lock (gate) { running--; completed++; } } finally { semaphore.Release(); } }); await Task.WhenAll(tasks); Console.WriteLine($"max in flight {max}"); Console.WriteLine($"completed {completed}");

dotnet run

max in flight 2
completed 5

Two tasks were inside at the most and all five finished. The try/finally is not decoration: a task that threw while holding a permit would never release it, and the semaphore would run out after two failures. WaitAsync is the asynchronous wait; Wait would block a thread until a permit is free.

The count of a semaphore

CurrentCount is the number of free permits, and the maximum is the second constructor argument. A wait with a timeout of zero asks whether a permit is free without waiting:

using var semaphore = new SemaphoreSlim(2, 2); Console.WriteLine($"count {semaphore.CurrentCount}"); Console.WriteLine($"wait {semaphore.Wait(0)}"); Console.WriteLine($"count {semaphore.CurrentCount}"); semaphore.Release(); Console.WriteLine($"count {semaphore.CurrentCount}"); Console.WriteLine($"try {semaphore.Wait(0)}"); semaphore.Release();

dotnet run

count 2
wait True
count 1
count 2
try True

The first wait took a permit and the count fell to one; the release gave it back and the count returned to two. A release beyond the maximum throws SemaphoreFullException, which is the bug of a program that releases twice for one wait. The second argument is what makes that check possible; without it the maximum is int.MaxValue. A release that would go past the maximum throws, and the message names the count:

var s = new SemaphoreSlim(1, 1); try { s.Release(); } catch (SemaphoreFullException e) { Console.WriteLine($"caught {e.GetType().Name}"); Console.WriteLine($"message {e.Message}"); } Console.WriteLine("end");

dotnet run

caught SemaphoreFullException
message Adding the specified count to the semaphore would cause it to exceed its maximum count.
end

Mutex

A Mutex counts to one and belongs to the thread that took it, so the same thread may take it again and must release it the same number of times. The program takes it, releases it and takes it again:

using var mutex = new Mutex(); Console.WriteLine($"mutex wait {mutex.WaitOne(0)}"); mutex.ReleaseMutex(); Console.WriteLine($"mutex again {mutex.WaitOne(0)}"); mutex.ReleaseMutex();

dotnet run

mutex wait True
mutex again True

Both waits succeeded, the second one because the thread owns the mutex and may re-enter it. A named mutex, new Mutex(false, "Global\MyApp"), is visible to other processes on the same machine, which is how two instances of a program agree that only one may run. A mutex is slower than a semaphore and it is not asynchronous: a task that waits on one blocks a thread, which is why a program that can use SemaphoreSlim should.

Which one to use

Exercises

  1. Change the limit to three and confirm the measured maximum.
  2. Throw inside the protected block and check that the permit is released.
  3. Release a semaphore of maximum two three times and read the exception.
  4. Start the same program twice with a named mutex and see the second wait.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does new SemaphoreSlim(2) allow?

    Answer

    Two waits to succeed before one has to release

    The constructor sets the initial and maximum count of permits.

  2. What does WaitAsync do when no permit is free?

    Answer

    Returns a task that completes when a permit is released

    The asynchronous wait lets the thread go while it waits.

  3. What does this program print? var s = new SemaphoreSlim(2); Console.WriteLine(s.CurrentCount);

    Answer

    2

    A new semaphore starts with the count of its constructor.

  4. What must follow every successful wait?

    Answer

    A Release, usually in a finally block

    A permit not returned is lost, and the semaphore runs out.

  5. What was the measured maximum of two in flight with SemaphoreSlim(2)?

    Answer

    2

    The program counted the tasks inside and printed max in flight 2.

  6. What is the difference between Mutex and SemaphoreSlim?

    Answer

    A Mutex is an OS object owned by a thread; SemaphoreSlim is an in-process counter

    A named mutex is visible to other processes, and it belongs to the thread that took it.

  7. What does this program print? var s = new SemaphoreSlim(0, 1); Console.WriteLine(s.Wait(10));

    Answer

    False

    The semaphore has no permit, so the wait with a timeout gives up and returns false.

  8. What does a release beyond the maximum throw?

    Answer

    SemaphoreFullException

    The maximum given to the constructor is enforced on release.

  9. What does this program print? var s = new SemaphoreSlim(2); Console.WriteLine(s.Wait(0));

    Answer

    True

    A permit is free, so the wait of zero takes it and returns true.

  10. Why is a named mutex useful?

    Answer

    It lets two processes of the same machine exclude each other

    The name is in the operating-system namespace, so another process can open it.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev