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.
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.
The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.
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.
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".
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.
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 ++
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With