简体   繁体   English

数组指针线程安全

[英]Array Pointer thread safety

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? 假设我们有一个C#数组,可以从多个线程访问该数组,那么在运行时更改该数组是否安全? (not as in to change its data, but to change the pointer). (不是更改其数据,而是更改指针)。 In other words, is writing an Array pointer an atomic operation? 换句话说,编写数组指针是原子操作吗?

Writing the address of a new pointer is an atomic operation: 编写新指针的地址是一个原子操作:

5.5 Atomicity of variable references 5.5变量引用的原子性

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. 下列数据类型的读写是原子的:bool,char,byte,sbyte,short,ushort,uint,int,float和引用类型。 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. 不保证其他类型的读取和写入(包括long,ulong,double和decimal)以及用户定义的类型都是原子的。

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. 为了避免缓存的副作用 ,您也可以使用volatile关键字。


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. 假设您将data数组设置为不同长度的数组,则for -loop可能会检查长度以获取旧数组的长度,然后将引用修改为较短的数组,然后访问非法索引。

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. 因此,非阻塞多线程应用程序将引用复制到数组,修改数组,然后检查引用是否被修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM