“volatile”在C ++中防止什么类型的优化? [英] What kinds of optimizations does 'volatile' prevent in C++?

查看:308
本文介绍了“volatile”在C ++中防止什么类型的优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查找关键字 volatile 和它的用途,我得到的答案是:

I was looking up the keyword volatile and what it's for, and the answer I got was pretty much:

它用于防止编译器优化代码。

It's used to prevent the compiler from optimizing away code.

当轮询内存映射硬件时:没有 volatile ,轮询循环将被删除,因为编译器可能识别条件值从未改变。但是由于只有一个例子或两个,它让我想:有没有其他情况下,我们需要使用 volatile 避免不必要的优化?条件变量是唯一需要 volatile 的地方吗?

There were some examples, such as when polling memory-mapped hardware: without volatile the polling loop would be removed as the compiler might recognize that the condition value is never changed. But since there only were one example or maybe two, it got me thinking: Are there other situations where we need to use volatile in terms of avoiding unwanted optimization? Are condition variables the only place where volatile is needed?

我认为优化是编译器特定的,因此没有在C ++规范中指定。这意味着我们必须通过直觉,说,如果我不声明这个变量为 volatile ,我怀疑我的编译器会消除这一点。

I imagine that optimization is compiler-specific and therefore is not specified in the C++ specification. Does that mean we have to go by gut feeling, saying Hm, I suspect my compiler will do away with this if I don't declare that variable as volatile or are there any clear rules to go by?

推荐答案

基本上, volatile 宣布一个值可能会改变你的程序的背后。这可以防止编译器缓存该值(在CPU寄存器中),并且当它们看起来不需要您的程序的POV时,可以优化对该值的访问。

Basically, volatile announces that a value might change behind your program's back. That prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of your program.

应该触发 volatile 的用法是当值改变时,尽管程序没有写入它,并且当没有其他内存障碍(如用于多线程程序的互斥体)存在。

What should trigger usage of volatile is when a value changes despite the fact that your program hasn't written to it, and when no other memory barriers (like mutexes as used for multi-threaded programs) are present.

这篇关于“volatile”在C ++中防止什么类型的优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆