gpt4 book ai didi

c++ - 优化 volatile 变量

转载 作者:行者123 更新时间:2023-11-30 05:03:57 24 4
gpt4 key购买 nike

我的理解是,C++ 标准要求对 volatile 对象的访问严格按照抽象机的规则进行评估。我确信这意味着无法更改给定 volatile 变量的加载和存储次数,也无法对这些访问进行重新排序。

但是关于其他非 volatile 访问的重新排序呢?

是否可以从 if 语句的两个分支中提升或隐藏完全冗余的 volatile 访问?例如。假设没有违反数据依赖关系可以

if (e) {
= non-volatile-load;
non-volatile-store =;
t = volatile-load;
= non-volatile-load;
non-volatile-store =;
} else {
= non-volatile-load;
non-volatile-store =;
t = volatile-load;
= non-volatile-load;
non-volatile-store =;
}

优化为

t = volatile-load;
if (e) {
= non-volatile-load;
non-volatile-store =;
= non-volatile-load;
non-volatile-store =;
} else {
= non-volatile-load;
non-volatile-store =;
= non-volatile-load;
non-volatile-store =;
}

或到

if (e) {
= non-volatile-load;
non-volatile-store =;
= non-volatile-load;
non-volatile-store =;
} else {
= non-volatile-load;
non-volatile-store =;
= non-volatile-load;
non-volatile-store =;
}
t = volatile-load;

如果 volatile-load 是 volatile-store 会怎样?

最佳答案

as-if rule下,...

... conforming implementations ... are required to emulate (only) the observable behavior of the abstract machine as explained below

observable behavior在下面指定为(强调我的)...

– Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.

所以是的,编译器可能会重新排序对非 volatile 变量的访问(当然在线程环境中的内存栅栏范围内;volatile 不提供这样的语义,atomic 确实)。

关于c++ - 优化 volatile 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com