Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, i.e. reading the value in _arr[i] is not guaranteed to be 'atomic' with the actual incrementing.

If I am correct in thinking this is wrong, how can I fix this? Thanks.

like image 820
user981225 Avatar asked Oct 08 '12 14:10

user981225


People also ask

What is interlocked increment?

The Interlocked Class in C# provides one static method called Increment. The Increment method increments a specified variable and stores the result, as an atomic operation.

Is interlocked increment thread safe?

The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.

What is interlocked exchange?

Interlock. Exchange returns the original value while performing an atomic operation. The whole point is to provide a locking mechanism. So it is actually two operations: read original value and set new value.

What is interlocked C#?

It lets you do small and well-defined operations safely in a multi-threaded environment: for instance, if you want two threads to increment the same variable, you can use Interlocked to do it instead of acquiring a heavyweight lock and using the "regular increment".


2 Answers

Assuming nothing changes i or _arr, that should be fine.

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.

like image 96
Jon Skeet Avatar answered Sep 28 '22 11:09

Jon Skeet


If something is asynchronously changing _arr or i then, I'd agree with you, no, the lookup _arr[i] is not necessarily atomic itself.

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.

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. (And then you can reduce the Interlocked.Increment to a simple ++.

like image 25
Mark Hurd Avatar answered Sep 28 '22 12:09

Mark Hurd