Atomicity (or Lack Thereof) Illustrated

To give a programming-related example of the need for synchronization, let’s keep things as simple as we can and take a look at a shared counter. None of the following code should be hard to understand at this point. We simply create and start a new thread to increment the counter repeatedly. In the meantime, the main thread performs its duties, decrementing the same counter value. Finally, we join the incrementing thread (called up) with the main thread and print the result.

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

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

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