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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.