安全读取元素同时更改的long []内容的最快方法 [英] Fastest way to safely read contents of long[] whose elements are changed concurrently
问题描述
当你有一个
long[] myArray = new long[256];
使用多个线程更改了其项目
whose items are changed by multiple threads using
Interlocked.Increment(ref myArray[x])
肯定不会在某个时间点获得myArray
的快照,因为同时发生了非锁定写入,因此我不打算这样做.
it sure won't be possible to get a snapshot of myArray
at one point in time, as there are non-locked writes going on concurrently, so I'm not trying to get that.
那么我真的必须对每个这样的元素进行Volatile.Read
来获得过去某个时候所有值的副本吗?
So do I really have to Volatile.Read
of every single element like this to get a copy of all values at some point in the past?
long[] copy = new long[256];
for (int i = 0; i < 256; i++)
copy[i] = Volatile.Read(ref myArray[i]);
由于我对某一时刻的快照不感兴趣,所以过时的值不是问题,但是由于64位非易失性读取不是原子的,因此我担心以下内容可能会给我带来预增的作用长度的一半,以及后增量的一半,这可能会提供数组中从未存在的值.
As I'm not interested in a snapshot at one point in time, stale values are not a problem, but as 64-bit non-volatile reads are not atomic, I fear that the following may give me a pre-increment half of a long, and a post-increment half, which may give a value that never existed in the array.
long[] copy = new long[256];
for (int i = 0; i < 256; i++)
copy[i] = myArray[i];
鉴于我不想使用任何锁定功能,因此Volatile.Read
变体是正确的选择吗?
So is the Volatile.Read
variant the proper choice, given I don't want to use any locking?
推荐答案
如果过时的值对您而言不是问题,而您所需的只是原子读取(不是有序读取),则在x64上,您可以使用普通读取而不是Volatile.Read
.
在使用DMB实现易失性读写的ARM系统上,这可能是有益的.
If stale values is not an issue for you and all you need is atomic read (not ordered one) then on x64 you can just use plain read instead of Volatile.Read
.
It can be beneficial on on ARM systems where volatile reads/writes are fairly heavyweight as they are implemented with DMB.
重要 根据此和那,您需要在64位模式下(构建和)运行.Net程序,这样才能正常工作:
Important According to this and that, you need to (build and) run your .Net program in 64-bit mode for this to work:
如果要在64位操作系统上以64位运行C#代码 版本的CLR然后读取和写入64位double和long 整数也保证是原子的
if you are running C# code on a 64 bit operating system in a 64 bit version of the CLR then reads and writes of 64 bit doubles and long integers are also guaranteed to be atomic
这篇关于安全读取元素同时更改的long []内容的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!