V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
dinghao188
V2EX  ›  C++

关于 memory_order_relaxed

  •  
  •   dinghao188 · 2021-03-05 20:40:26 +08:00 · 930 次点击
    这是一个创建于 1140 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天看到 atomic 相关的东西,然后就顺到了关于 memory_order 的东西

    网上说下面的代码有可能会出现 r1 == 1111 && r2 == 1111 的情况,我运行了几万遍了,还是没碰到。还是说只是理论上会出现?大佬们怎么看?

    #include <iostream>
    #include <thread>
    #include <atomic>
     
    using namespace std;
     
    atomic_int x {0};
    atomic_int y {1};
     
    void func1() {
        int r1 = y.load(std::__1::memory_order_relaxed);
        x.store(r1, std::__1::memory_order_relaxed);
    }                                                                                                                                                               
     
    void func2() {
        int r2 = x.load(std::__1::memory_order_relaxed);
        y.store(1111, std::__1::memory_order_relaxed);
    }
     
    int main() {
        thread t1(func1);
        thread t2(func2);
        t1.join();
        t2.join();
    }
    
    codehz
        1
    codehz  
       2021-03-05 20:45:18 +08:00
    在 apple silicon 上就有效果了,intel 强制严格内存序
    dinghao188
        2
    dinghao188  
    OP
       2021-03-08 14:40:01 +08:00
    @codehz 原来是这样,改天试下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3173 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:12 · PVG 21:12 · LAX 06:12 · JFK 09:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.