Reputation: 387
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?
Upvotes: 9
Views: 1880
Reputation: 387
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);
Upvotes: 0
Reputation: 12956
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.
Upvotes: 1
Reputation: 144136
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);
Upvotes: 12