First of all, I tried to find out if using Interlocked requires a volatile field definition, and this is my real question.
But. Being too lazy to analyze the generated MSIL, I decided to test this in practice.
I am trying an MSDN example for using volatile when code should break in a release build with optimizations. And nothing will break. The code works fine (in this case, the main thread finishes gracefully) with optimization turned on and off.
- Should I still require the
volatile keyword in the field when I write to it from one thread using Interlocked and read from another thread without blocking? - A simple code example from question 1, where does
volatile make a difference? - Why does the MSDN example still work when I remove the
volatile keyword and build in the release?
code snippet to illustrate question 1.
class Example { volatile int val; void Do() { Task.Run(() => { while (val == 0) Console.WriteLine("running"); }); Thread.Sleep(1000); Interlocked.Increment(ref val); Console.WriteLine("done."); Console.ReadLine(); } }
source share