6

From what I understand, the 'volatile' modifier in C# has two effects:

  1. Inserts fences as necessary for the target processor
  2. Prevents certain compiler optimizations

On x86 / amd64, (1) is irrelevant. Those processors don't require fences for volatile semantics. (ia64 is different, though.)

So, we are down to (2). But, for examples that I tried, volatile does not make any difference to the jit-ted assembly.

My question is: Can you give an example of a C# code sample where adding a 'volatile' modifier on a field results in different jit-ted assembly code?

Igor ostrovsky
  • 7,282
  • 2
  • 29
  • 28

2 Answers2

2

Maybe this is what you are looking for.

Community
  • 1
  • 1
tanascius
  • 53,078
  • 22
  • 114
  • 136
  • Awesome, that's exactly what I was looking for! Here, volatile indeed results in different assembly code. – Igor ostrovsky Feb 19 '10 at 09:57
  • In case anyone is curious, without a volatile modifier, the field value gets cached in a register. And, when the value is in a register, the looping core will never 'notice' the update done by another core. – Igor ostrovsky Feb 19 '10 at 10:01
1

Marc Gravell has an repeatable example of how the lack of a volatile keyword can cause problems.

It's also discussed here.

It's worth noting (as Marc does) that the compiler optimisations are only seen when compiled in Release mode.

Community
  • 1
  • 1
Simon P Stevens
  • 27,303
  • 5
  • 81
  • 107