Is C # + = thread safe?

I just came across a program where + = is used for a common variable among threads, so + = is thread safe, i.e. performs addition and assignment atomically?

+6
source share
4 answers

No, it is not thread safe, as it is equivalent to:

int temp = orig + value; orig = temp; 

Instead, you can use Interlocked.Add :

 Interlocked.Add(ref orig, value); 
+7
source

Do you want to

 System.Threading.Interlocked.Add() 
+1
source
 string s += "foo"; 

there is

 string s = s + "foo"; 

s read and then reassigned. If between these two actions the value of s changed by another thread, the result will be different, therefore, it will not be thread safe.

0
source

Thanks to everyone for the quick answers. Yes, + = is not thread safe and the following simple program may be run to verify this.

int count = 0;

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

code>

0
source

Source: https://habr.com/ru/post/955809/


All Articles