Reputation: 6049
Let's assume we have an array in C# which is accessed from mutliple threads, is it thread safe to change this array in runtime? (not as in to change its data, but to change the pointer). In other words, is writing an Array pointer an atomic operation?
Upvotes: 2
Views: 369
Reputation: 477854
Writing the address of a new pointer is an atomic operation:
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.
Since an array pointer is a reference, it is thread safe.
In order to avoid cache side-effects, you can use the volatile
keyword as well.
However you must be very carefull with this. Say you have a method:
public class Foo {
private volatile int[] data;
public void Method () {
for(int i = 0; i < data.length; i++) {
data[i] = i;
}
}
public void OtherMethod (int[] data) {
this.data = data;
}
}
Say you set the data
array to an array with a different length, it is possible that the for
-loop checks the length fetches the length of the old array, then the reference is modified to a shorter array and then you access an illegal index.
Non-blocking multithreaded applications, therefore make a copy of the reference to the array, modify the array and then check if the reference is modified.
Upvotes: 6