9

Just ran into a program where += is used on a shared variable among threads, so is += thread safe, i.e. performs addition and assignment atomically?

Saliya Ekanayake
  • 387
  • 3
  • 10

4 Answers4

12

No it isn't thread safe since it's equivalent to:

int temp = orig + value;
orig = temp;

You can use Interlocked.Add instead:

Interlocked.Add(ref orig, value);
Lee
  • 142,018
  • 20
  • 234
  • 287
2

You want

System.Threading.Interlocked.Add()
Mike Goodwin
  • 8,810
  • 2
  • 35
  • 50
1
string s += "foo";

is

string s = s + "foo";

s is read and then re-assigned. If in between these two actions the value of s is changed by another thread, the result with be different, so it's not thread safe.

Sam Leach
  • 12,746
  • 9
  • 45
  • 73
0

Thank you all for the quick replies. Yes, += is not thread safe and to verify this one may run the following simple program.

int count = 0;

        Parallel.For(0, 10000, i =>
        {
            count +=1; // not thread safe
        });
        Console.WriteLine(count);

Saliya Ekanayake
  • 387
  • 3
  • 10