[英]Interlocked.Increment an integer array
Is this guaranteed to be threadsafe/not produce unexpected results? 这是保证线程安全/不会产生意外结果吗?
Interlocked.Increment(ref _arr[i]);
My intuition tells me this is not, ie reading the value in _arr[i] is not guaranteed to be 'atomic' with the actual incrementing. 我的直觉告诉我这不是,即读取_arr [i]中的值并不能保证在实际递增时是“原子的”。
If I am correct in thinking this is wrong, how can I fix this? 如果我认为这是错误的,我该如何解决这个问题呢? Thanks.
谢谢。
Assuming nothing changes i
or _arr
, that should be fine. 假设
i
或_arr
没有任何变化,那应该没问题。
An array is regarded as a collection of variables; 数组被视为变量的集合; an interlocked increment should work fine regardless of what is happening to either that element or others in the same array.
互锁增量应该正常工作,无论该元素或同一数组中的其他元素发生了什么。
If something is asynchronously changing _arr
or i
then, I'd agree with you, no, the lookup _arr[i]
is not necessarily atomic itself. 如果事情是异步改变
_arr
或i
的话,我同意你的观点,不,查找_arr[i]
是不是原子本身。
However, as Jon says, once you have identified an element of (some) _arr
, it will be atomically incremented, independent of other actions happening in other elements of the array(s), or to further changes to _arr
or i
. 然而,正如Jon所说,一旦你确定了(某些)
_arr
的元素, 它将以原子方式递增,独立于阵列的其他元素中发生的其他动作,或者进一步更改为_arr
或i
。
If _arr
or i
are being asynchronously changed, all references to them ( both read and write) need to be inside a lock
on a common object. 如果
_arr
或i
正在异步改变,对他们的所有引用( 读 ,写)需要一个内部lock
一个共同的对象。 (And then you can reduce the Interlocked.Increment
to a simple ++
. (然后你可以将
Interlocked.Increment
简化为一个简单的++
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.