关于 memory_order_relaxed

2021-03-05 20:40:26 +08:00
 dinghao188

今天看到 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();
}
940 次点击
所在节点    C++
2 条回复
codehz
2021-03-05 20:45:18 +08:00
在 apple silicon 上就有效果了,intel 强制严格内存序
dinghao188
2021-03-08 14:40:01 +08:00
@codehz 原来是这样,改天试下

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/758920

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX