3

Two threads. The first furiously reading elements from the array. The second is equally furious in updating elements by reading them and incrementing them by an arbitrary amount.

Is this safe? can anything go wrong in this situation? I don't mind that the reading thread reads an 'old' value while the updating thread is still in the process of updating. I just want to make sure the reader doesn't ever read a number that was not written and also that an exception cannot occur.

3
  • I've updated to explain what I don't want to happen Commented Sep 23, 2013 at 16:51
  • There will be no exception. There wouldn't even be an exception if "half-written" updates could happen, which they can't. Commented Sep 23, 2013 at 16:55
  • Do you have any requirement that a third thread that is also reading the array sees a consistent ordering of the operations of the other two threads? Because that is not guaranteed by the C# memory model without introducing barriers. Commented Sep 23, 2013 at 17:41

2 Answers 2

9

An int update is atomic on all cpu architectures that can execute managed code. In other words, you won't read a value that has just a single byte modified by the writing thread. Value type values larger than 32-bit, like long and double are not guaranteed atomic. Object references are also always atomic.

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

2 Comments

long must be atomic on x86-64, and also memory pointers are atomic
@SargeBorsch: To be picky: the C# language guarantees that pointers and references are atomic on all architectures when aligned. Though the runtime or the hardware might make a guarantee for longs, the C# language does not.
1

That isn't thread-safe - you aren't guaranteed that one thread gets the proper data.

4 Comments

But can you be guaranteed that the reading thread will read either new or old data, rather than some other irrelevant data?
It doesn't appear that he's concerned about stale reads, only about potential run time exceptions, making me fear for the place this implementation is occuring.
don't worry preston, it's just some autopilot code I am writing for the aircraft that flies around our nuclear power plant
If that's all, I suggest doing away with the array at all and returning Rand.Next() on every call.

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.