Mutex and Semaphore

Explore additional thread synchronization primitives.

We'll cover the following

Synchronization using mutex

The word mutex stands for mutual exclusion. It’s a special object that can restrict access to a critical section of the code. In essence, there’s nothing much that separates a mutex from the lock statement or the Monitor class. We create a mutex object and, whenever we enter a critical section, we acquire the lock for the mutex. If the mutex has already been acquired by another thread, then the thread has to wait until the mutex is released.

Note: The mutex in .NET is represented by a class called Mutex, which resides in the System.Threading namespace.

Unlike the lock statement and Monitor, Mutex doesn’t need a separate locker object because it serves this purpose itself:

// Mutex
static Mutex mutex = new Mutex();

static void SomeMethod()
    // Critical section begins here
        // Critical section code
        // Release the mutex

Notice that there’s almost no difference in structure between Mutex and Monitor. The only notable difference is that we haven’t created an empty object instance as a locker. The Mutex instance uses itself as this locker object.

The main synchronization is done by the WaitOne() and ReleaseMutex() methods. The WaitOne() method suspends thread execution until the mutex object is obtained.

Initially, the mutex is free, so one of the threads gets it.

After all actions have been completed and the mutex is no longer needed, the thread releases it using the ReleaseMutex() method. Then, the mutex is acquired by one of the waiting threads.

When execution reaches a call to WaitOne(), the thread waits until the mutex is released. After receiving it, it continues to do its job.

Get hands-on with 1200+ tech skills courses.