'volatile' 在 C++ 中阻止了哪些优化? [英] What kinds of optimizations does 'volatile' prevent in C++?

查看:50
本文介绍了'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天全站免登陆