1

A few days ago I read the following article about the C# Memory Model: http://msdn.microsoft.com/en-us/magazine/jj863136.aspx

This article states that the JIT compiler is allowed to reorder memory operations when ordinary (that is, non-volatile) fields are being used.

Figure 9 demonstrates an example of a polling loop that is supposed to be broken:

class PollingLoopExample
{
  private bool _loop = true;
  public static void Main()
  {
    PollingLoopExample test1 = new PollingLoopExample();
    // Set _loop to false on another thread
    new Thread(() => { test1._loop = false;}).Start();
    // Poll the _loop field until it is set to false
    while (test1._loop) ;
    // The previous loop may never terminate
  }
}

The text states that on x86 and x64 archtectures, the polling loop example will typically hang. Immediately I was trying this out on my own, but regardless how often I was running it, the polling loop didn't hang a single time.

This brings me to the question why it doesn't work anymore (assuming that it had been workking in the past). I can imagine that this issue has been solved by a bug fix or a more recent version of .NET.

So what are the causes of this issue? I hope someone can give me a specific answer.

Dennis Kassel
  • 2,726
  • 4
  • 19
  • 30

0 Answers0