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?
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);
You want
System.Threading.Interlocked.Add()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With