11

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.

1
  • Who or what is reading the value in _arr[i]? This code doesn't read it, it increments it atomically because that's what Interlocked.Increment does. Commented Oct 8, 2012 at 14:33

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ++.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.