Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array write atomic in C#?

Tags:

var a = new bool[]{true,false};
var b = new bool[4];
a=b;       //operation 1
a[1]=true; //operation 2

I know that there are some atmoic types defined in C# ,from where I can't find array.

  1. Opration 1 is something like a pointer reassignment. Does it guarantee to be atmoic?
  2. How about operation 2?
like image 410
joe Avatar asked Jun 29 '17 02:06

joe


1 Answers

Operation 1 is atomic. Operation 2 is not. From the spec:

5.5 Atomicity of variable references

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

Arrays are reference types. Variable a and b are references, and so Operation 1 is a reference assignment: a simple write to a reference variable, and so is included. Operation 2 looks like a simple write to a bool, which would also be included, but don't forget the index lookup in the array. The array write itself is atomic, but when you include the lookup (dereferencing a[1]) there are two separate operations involved.

like image 147
Joel Coehoorn Avatar answered Oct 11 '22 14:10

Joel Coehoorn