编译器是否可以优化两个原子负载? [英] Can and does the compiler optimize out two atomic loads?

查看:74
本文介绍了编译器是否可以优化两个原子负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,两个负载会合并为一个吗? 如果这取决于体系结构,那么来自Intel的现代处理器将如何处理?我相信原子负荷等同于英特尔处理器中的正常负荷.

Will the two loads be combined to one in such scenarios? If this is architecture dependent, what would be the case in say modern processors from say Intel? I believe atomic loads are equivalent to normal loads in Intel processors.

void run1() {
    auto a = atomic_var.load(std::memory_order_relaxed);
    auto b = atomic_var.load(std::memory_order_relaxed);
   // Some code using a and b;
}

void run2() {
    if (atomic_var.load(std::memory_order_relaxed) == 2 && /*some conditions*/ ...) {
         if (atomic_var.load(std::memory_order_relaxed) * somevar > 3) {
               /*...*/
         }
    }
}

run1()run2()只是使用相同原子变量的两次加载的两种情况.编译器能否将两个负载合并为一个负载并重用该场景?

run1() and run2() are simply two scenarios using two loads of the same atomic variable. Can the compiler collapse such scenarios of two loads into one load and reuse that?

推荐答案

编译器可以优化原子负荷吗?

您可以将run1()的实现安全地优化为

Can the compiler optimize away atomic loads?

Your implementation of run1() can be safely optimized to

void run1() {
    auto a = atomic_var.load(std::memory_order_relaxed);
    auto b = a;
   // Some code using a and b;
}

在原始程序中,每次调用run1()时,两个负载可能按照对atomic_var的总访问顺序彼此相邻.在这种情况下,相邻的load()操作将返回相同的结果.

In the original program the two loads could possibly be adjacent to each other in the total order of accesses on atomic_var every time run1() is called. In that case the adjacent load() operations would return the same result.

由于不能排除这种可能性,因此允许编译器优化第二个load().可以对任何内存顺序参数执行此操作,而不仅仅是针对宽松的原子.

Since that possibility cannot be excluded, the compiler is allowed to optimize away the second load(). This can be done for any memory order argument, not just for relaxed atomics.

对于run2(),取决于.您未指定/*some conditions*/.如果存在某些问题,可能会对原子变量产生明显的副作用(例如不透明的函数调用或访问易失性变量等),那么就无法对其进行优化.否则有可能.

For run2() it depends. You didn't specify /*some conditions*/. If there's something, that might have a visible side effect on the atomic variable (like an opaque function call or accessing a volatile variable, etc.) then this cannot be optimized away. Otherwise it might be possible.

取决于您的编译器.可能还取决于您传入的编译器选项.可能取决于您的平台.关于编译器是否应该优化原子的争论一直在进行.有 N4455没有Sane编译器会优化原子学这部视频作为该主题的开始.

Depends on your compiler. And possibly on the compiler options you passed in. Possibly it depends on your platform. There is some debate going on, on whether compilers should optimize atomics. There is N4455 No Sane Compiler Would Optimize Atomics and this video as a start on the topic.

GCC和clang目前没有将两个load()操作优化为一个.

GCC and clang don't optimize the two load() operations onto one at the moment.

这篇关于编译器是否可以优化两个原子负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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