Could this C # code crash due to a value in a register or cache that is never retrieved back to main memory?

In this article:

http://msdn.microsoft.com/en-us/magazine/jj883956.aspx

The author declares that the following code may fail due to “loopback reading”:

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 raise mode, the compiler can change the while loop above to the following due to a single-threaded assumption:

if (_flag) { while (true); }

, : , , - _flag , ? , " # ", , , , ECMA, ARM . , , .

:

# ?

, , , , ...

+4
1

, , - , _flag , ?

.

, " # ", , , , ECMA, ARM .

? , .

, , , .

, . . , : .

, , , . , , , - , , . " ", CancellationToken; . " ", Task<T>; . ; Microsoft .

UPDATE: #, , , , .

2005 :

http://msdn.microsoft.com/en-us/magazine/cc163715.aspx

, 2011 :

http://ericlippert.com/2011/05/26/atomicity-volatility-and-immutability-are-different-part-one/

, , .

, volatile:

http://joeduffyblog.com/2010/12/04/sayonara-volatile/

2014 Ask The Bug Guys:

http://blog.coverity.com/2014/03/12/can-skip-lock-reading-integer/ http://blog.coverity.com/2014/03/26/reordering-optimizations/

; Vance, , .

+6

Source: https://habr.com/ru/post/1536788/


All Articles