简体   繁体   English

volatile是否会成为优化的编译器障碍

[英]Does volatile act as a compiler barrier for optimization

Is the compiler allowed to optimize the code flow by moving statements (not parts of an expression) from before a volatile access to afterwards, or from after a volatile access to before it. 是允许编译器通过将语句(不是表达式的一部分)从volatile访问之前移到之后,还是从volatile访问之后移到它之前来优化代码流。

In reference to my answer to SO : is volatile required for synchronous ISR access 关于我对SO的回答:同步ISR访问需要挥发性的

Objections to my answer has suggested that the use of volatile does not cause the generalized machine for C++ (and C) to ensure that all operations before hand are completed. 对我的回答的反对意见表明,使用volatile不会导致C ++(和C)通用机器确保完成所有手工操作。

My reading of cppreference : const volatile 我对cppreference的阅读:const volatile

that is, within a single thread of execution, volatile accesses cannot be optimized out or reordered with another visible side effect that is sequenced-before or sequenced-after the volatile access. 也就是说,在单个执行线程中,无法优化易失性访问,也不会因易失性访问之前或之后的另一个可见副作用而被优化或重新排序。 This makes volatile objects suitable for communication with a signal handler, but not with another thread of execution 这使得易失性对象适合与信号处理程序进行通信,但不适合与其他执行线程进行通信

Is that for the case in my answer - single core operation the following should be true. 在我的答案中是否是这种情况-单核操作,以下内容应该正确。

  • The results are visible as fast as possible - there may be a point where a change to a volatile hasn't been written, but if it is written, then the single core would see it in a signal handler, (or an ISR). 结果尽可能快地可见-可能在某个时候尚未写入对volatile的更改,但是如果写入了更改,则单核将在信号处理程序(或ISR)中看到它。
  • A compliant C++ compiler would not be able to re-order operations around the volatile write as it is a visible side effect. 兼容的C ++编译器将无法对易失性写进行重新排序,因为这是显而易见的副作用。

My answer on this thread assumed the particular case was a single core CPU, and that C++11 was not applicable, so I would prefer answers within that scope. 我对此线程的回答假设特定情况是单核CPU,并且C ++ 11不适用,所以我希望在该范围内回答。

The C++ standard does not distinguish between what the code flow says and what the code does. C ++标准没有区分代码流说什么和代码做什么。 So this, and all questions about code flow rather than observable behavior, is a platform-specific question. 因此,所有有关代码流而不是可观察行为的问题都是特定于平台的问题。

A compliant C++ compiler would not be able to re-order operations around the volatile write as it is a visible side effect. 兼容的C ++编译器将无法对易失性写进行重新排序,因为这是显而易见的副作用。

Nobody understands the standard to say that. 没有人知道这个标准。 This is why x86 compilers do not put memory barriers around volatile operations and do permit re-ordering by the CPU. 这就是为什么x86编译器不会volatile操作周围设置内存障碍,并允许CPU重新排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM