Mutual exclusion of code executing simultaneously is the essential idea to tame the concurrency monster. In fact, the concept of a mutex got its name from it. Semaphores are the generalization of mutexes and are discussed in the next section.

Using a mutex, we could make our running example thread safe as follows. This piece of code illustrates the two main operations invoked with a mutex:

static void Main(){    var mutex = new Mutex();    int n = 0;    var up = new Thread(() =>    {        for (int i = 0; i < 1000000; i++)        {            mutex.WaitOne();            n++;            mutex.ReleaseMutex();        }    });    up.Start();    for (int i = 0; i < 1000000; i++)    {        mutex.WaitOne();

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.