#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.
                Interlocked.Increment(ref counter2);

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


Note below that Counter #1 is not incremented properly.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – May 20, 2014 (#1780) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: