-
I was trying to understand the precise meaning of The example that is provided illustrates that very well. However it also contains a polling loop checking the volatile field. This is interesting because it concerns another optimisation, namely pulling the flag check out of the loop (hoisting). If you look at the .NET Core JIT assembly you see that without The CLR ECMA-335 (5th ed) standard seems to call this out in sections 12.6.4 and 12.6.7:
However the C# specification does not seem to make any of these guarantees for volatile, so I was wondering whether some other part of the standard explains why this code is supposed to work? In this 2012 MSDN Magazine article about memory models the author poses the same question:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
.NET implements stricter memory model than ECMA defines. |
Beta Was this translation helpful? Give feedback.
I think this is a possible interpretation, Stephen, however the section talks about reorderings in the instruction sequence without defining the term precisely (at least I was not able to find it; the only thing I was able to deduce is that it’s about the temporal sequence of instructions not the instruction as they are laid out in the code listing).
The question is whether other optimisations leading to non-reordering changes (as a non-benevolent reader might argue that collapsing the reads is not a reordering) are also prohibited.
Funnily, since I had to go through the C# spec again, I found section 7.10 which talks about the preservation of side effects:
Emphasis mine: