Best practice for using the 'volatile' keyword in VS2012

邮差的信 提交于 2019-12-23 09:18:34

问题


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 as std::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:

  1. Should we remove uses of 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?
  2. If we don't do the above, is there any downside?

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.


回答1:


  1. If you have the time for it. The benefits are not that great - C++11 atomics may allow more precise control over precisely what kind of synchronization you need, and have more clearly defined semantics, which may allow the compiler to optimize the code better.
  2. In theory, but very very unlikely, a future version of the compiler might drop support for the MS-style volatile completely. Or one day you actually do want to port away from the MS compiler, even if you stay on Windows. If you're now doing refactoring, that might be a good time to do the work of replacing the volatiles with atomics, saving you from doing the work in the future.


来源:https://stackoverflow.com/questions/16340899/best-practice-for-using-the-volatile-keyword-in-vs2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!