O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required