In this article:
http://msdn.microsoft.com/en-us/magazine/jj883956.aspx
the author states that the following code can fail due to "loop read hoisting":
class Test
{
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 loop read hoisting, the compiler may change the while loop above to the following because of a single-thread assumption:
if (_flag) { while (true); }
What I'm wondering is this: if the compiler doesn't perform that optimization, is there still potential for the loop to run forever on a multiprocessor machine due to one processor updating _flag in a register or cache and never flushing that cache back to memory readable by the other thread? I've read that "C# writes are volatile," but the article I linked to says this is not actually guaranteed by the ECMA spec and things aren't implemented that way on ARM. I'm trying to figure out how paranoid I have to be to write threaded code that will work on all platforms.
Here is a related question:
Can a C# thread really cache a value and ignore changes to that value on other threads?
but I think the code in the accepted answer is probably getting optimized with loop read hoisting, so it proves nothing about memory visibility...