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?
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
Interlocked.Add(ref orig, value);
Do you want to
System.Threading.Interlocked.Add()
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.
s
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>
Source: https://habr.com/ru/post/955809/More articles:Bash wait for the process to begin - bashGoogle calendar v3 returns 403 Not enough permission - ruby-on-railsIMEI / 01 Code - androidEasy way to fake freely defined Python recorder objects - pythongstreamer: How to do streaming through TLS? - sslHow do entire networks and CNSetSupportedSSID work? - iosAccurate loader on S3 bucket receiving error 405 Error not allowed - phpZurb Foundation "Joyride": how to start / programmatically - javascriptKey data: "NSObjectInaccessibleException" when trying to delete. - iosWriting to multiple folders in hadoop? - hadoopAll Articles