Can the compiler drop volatile reads when it thinks they are not usefull? RRS feed

  • Question

  • Hello.

    Think about the case where you have one (and one only) main thread that changes some data and some background threads that only reads it.


    class MyClass


     volatile bool _Volatile=true;

     TimeSpan _Data;

     void MainThreadUpdate(TimeSpan tsNewValue)



      _Volatile=true; // Volatile write



     void BackgroundThread()




       bool b=_Volatile; // Volatile read

       // Do some work with _Data.





    Is there any risk of the compiler dropping either:

    the _Volatile=true line if it notices that the value never changes,

    the bool b=_Volatile line if it notices that b is not used?


    Or will the compiler notice that these lines have an effect due to the volatile keyword, keep them executing and thus ensure that no background thread will read an old _Data from its cache for all eternity?


    Thanks. ;)

    Saturday, September 11, 2010 9:06 AM