My colleague and I are having an argument on atomicity of reading a double on an Intel architecture using C# .NET 4.0. He is arguing that we should use Interlocked.Exchange
method for writing into a double
, but just reading the double value (in some other thread) is guaranteed to be atomic. My argument is that .NET doesn't guarantee this atomicity, but his argument is that on an Intel architecture this is guaranteed (maybe not on AMD, SPARC, etc.).
Any Intel and .NET experts share some lights on this?
Reader is OK to read a stale (previous) value, but not incorrect value (partial read before and after write giving a garbage value).
Yes and no. On 32-bit processors, it is not guaranteed atomic, because double is larger than the native wordsize. On a 64-bit processor properly aligned access is atomic. The 64-bit CLI guarantees everything up to a 64-bit read as atomic. So you'd need to build your assembly for x64 (not Any CPU). Otherwise if your assembly may be run on 32-bit, you better use Interlocked, see Atomicity, volatility and immutability are different, part two by Eric Lippert. I think you can rely on Eric Lippert's knowledge of the Microsoft CLR.
The ECMA CLI standard also supports this, even though C# itself does not guarantee it:
A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic (see §I.12.6.2)
It also says that on processors where operations are atomic, Interlocked methods are often compiled to a single instruction, so in my book there is no performance penalty in using it. On the other hand, there may be a worse penalty to not using it when you should.
Another related Stack Overflow question is What operations are atomic in C#?.