https://msdn.microsoft.com/en-us/magazine/jj883956.aspx
Consider the polling loop pattern:
private bool _flag = true; public void Run() { // Set _flag to false on another thread new Thread(() => { _flag = false; }).Start(); // Poll the _flag field until it is set to false while (_flag) ; // The loop might never terminate! }In this case, the .NET 4.5 JIT compiler might rewrite the loop like this:
if (_flag) { while (true); }In the single-threaded case, this transformation is entirely legal and, in general, hoisting a read out of a loop is an excellent optimization. However, if the _flag is set to false on another thread, the optimization can cause a hang.
Note that if the _flag field were volatile, the JIT compiler would not hoist the read out of the loop. (See the “Polling Loop” section in the December article for a more detailed explanation of this pattern.)
Will the JIT compiler still optimize the code as shown above if I lock _flag or will only making it volatile stop the optimization?
Eric Lippert has the following to say about volatile:
Frankly, I discourage you from ever making a volatile field. Volatile fields are a sign that you are doing something downright crazy: you're attempting to read and write the same value on two different threads without putting a lock in place. Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given chunk of memory at a time, and so on. The number of situations in which a lock is too slow is very small, and the probability that you are going to get the code wrong because you don't understand the exact memory model is very large. I don't attempt to write any low-lock code except for the most trivial usages of Interlocked operations. I leave the usage of "volatile" to real experts.
To summarize: Who ensures that the optimization mentioned above doesn't destroy my code? Only volatile? Also the lock statement? Or something else?
As Eric Lippert discourages you from using volatile there must be something else?
Downvoters: I appreciate every feedback to the question. Especially if you downvoted it I'd like to hear why you think this is a bad question.
A bool variable is not a thread synchronization primitive: The question is meant as a generell question. When will the compiler not do the optimizion?
Dupilcate: This question is explicitly about optimizations. The one you linked doesn't mention optimizations.