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?
Asked
Active
Viewed 1,611 times
9
-
3No, it's not. It's writing to a variable. – Sam Leach Oct 11 '13 at 20:47
-
4No. It's reading, doing the addition, and then writing to the variable. It is not atomic. – Gray Oct 11 '13 at 20:48
-
2Autoincrement needs to be interlocked to be thread-safe. – RBarryYoung Oct 11 '13 at 20:49
-
1This may help http://stackoverflow.com/questions/4628243/is-the-operator-thread-safe?rq=1. And the answer is Never – Sriram Sakthivel Oct 11 '13 at 20:49
4 Answers
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
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