Since upgrading our development and build environments from VS2008 to VS2012, I am confused about the implications of using the volatile
keyword in our legacy codebase (it's quite extensive as there is a much copied pattern for managing threads from the "old" days).
Microsoft has the following remarks in the VS2012 documentation:
If you are familiar with the C# volatile keyword, or familiar with the behavior of volatile in earlier versions of Visual C++, be aware that the C++11 ISO Standard volatile keyword is different and is supported in Visual Studio when the
/volatile:iso
compiler option is specified. (For ARM, it's specified by default). The volatile keyword in C++11 ISO Standard code is to be used only for hardware access; do not use it for inter-thread communication. For inter-thread communication, use mechanisms such asstd::atomic<T>
from the C++ Standard Template Library.
It goes on to say:
When the
/volatile:ms
compiler option is used—by default when architectures other than ARM are targeted—the compiler generates extra code to maintain ordering among references to volatile objects in addition to maintaining ordering to references to other global objects.
I take this to mean, that our existing code won't break but won't necessarily be portable (not a problem for us).
However, it does raise these questions, on which I would like some advice, if possible:
volatile
qualifiers in our our code and replace with C++11 ISO Standard compliant equivalents, even though we would not port the code away from MS?I appreciate that this is not really a specific programming problem but we're embarking on some quite major refactoring and I would like to be able to offer some sensible guidelines for this work.
Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.
The volatile keyword in C++11 ISO Standard code is to be used only for hardware access; do not use it for inter-thread communication. For inter-thread communication, use mechanisms such as std::atomic<T> from the C++ Standard Library.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
The volatile keyword must be used when declaring shared memory that can be modified by threads in other blocks to guarantee that the compiler will not load the shared memory location into a register.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With