Search⌘ K
AI Features

Mutex and Semaphore

Explore how Mutex provides exclusive access to resources by allowing only one thread at a time, while Semaphore controls multiple concurrent threads. Understand these synchronization techniques to manage shared resources safely in multithreaded C# applications.

We'll cover the following...

Synchronization using Mutex

The word mutex stands for mutual exclusion. It is a synchronization primitive that grants exclusive access to a shared resource to only one thread at a time.

Functionally, a Mutex behaves similarly to the lock ...

C# 14.0
using System.Threading;
long balance = 0;
// We create a Mutex instance to act as our lock
using Mutex mutex = new Mutex();
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(Deposit);
threads[i].Start();
}
foreach (var t in threads) t.Join();
Console.WriteLine($"Expected Balance: 100,000,000");
Console.WriteLine($"Actual Balance: {balance:N0}");
void Deposit()
{
for (int i = 0; i < 100000; i++)
{
// We wait until the mutex is free
mutex.WaitOne();
try
{
// Critical section
balance = balance + 100;
}
finally
{
// We release the mutex so others can enter
mutex.ReleaseMutex();
}
}
}
  • Line 7: We ...