#1,100 – Increment and Decrement Operators Are Not Thread-Safe

If you have multiple threads increment or decrementing a variable using the increment or decrement operators, you may not get the desired result.  These operators are not thread-safe.

Imagine two threads that increment a variable.  If they do the operation serially, the variable ends up correctly incremented twice.  If the two threads read the value at the same time, however, they may both end up writing the same value back to the variable.  The variable ends up incremented just once.

You can do a safe increment operation using System.Threading.Threadlocked.Increment.

        private static int counter1 = 0;
        private static int counter2 = 0;

        static void Main(string[] args)
        {
            int maxExclusive = 1001;

            Parallel.For(1, maxExclusive, n =>
            {
                // Do some work here.
                Thread.Sleep(4);
                counter1++;
                Interlocked.Increment(ref counter2);
            });

            Console.WriteLine(
                "Ran {0} iterations, counter 1 = {1}, counter 2 = {2}",
                maxExclusive - 1, counter1, counter2);

            Console.ReadLine();
        }

Note below that Counter #1 is not incremented properly.
1100-001

Advertisements