Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of 'volatile' preventing a compiler optimization in C#?

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?

like image 744
Igor ostrovsky Avatar asked Feb 19 '10 09:02

Igor ostrovsky


2 Answers

Maybe this is what you are looking for.

like image 165
tanascius Avatar answered Nov 04 '22 02:11

tanascius


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.

like image 31
Simon P Stevens Avatar answered Nov 04 '22 00:11

Simon P Stevens