相关疑难解决方法(0)

memory_order_relaxed有哪些用例

C++内存模型具有宽松的原子性,它不会对内存操作进行任何排序保证.除了我在这里找到的C中的邮箱示例:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1525.htm

基于本文中的激励示例:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2153.pdf

我很好奇这种同步机制的其他用例.

c++ memory-model

10
推荐指数
1
解决办法
2795
查看次数

了解 memory_order_relaxed

我试图了解 memory_order_relaxed 的细节。我指的是这个链接:CPP 参考

#include <future>
#include <atomic>

std::atomic<int*> ptr {nullptr};

void fun1(){
        ptr.store(new int{0}, std::memory_order_relaxed);
}

void fun2(){
        while(!ptr.load(std::memory_order_relaxed));
}

int main(){
        std::async(std::launch::async, fun1);
        std::async(std::launch::async, fun2);
}
Run Code Online (Sandbox Code Playgroud)

问题1:在上面的代码中,即使设置ptr的线程已经完成运行,fun2在技术上是否可能处于无限循环中,它看到ptr的值为nullptr?

如果假设,我将上面的代码更改为如下所示:

#include <future>
#include <atomic>

std::atomic<int> i {0};
std::atomic<int*> ptr {nullptr};

void fun1(){
        i.store(1, std::memory_order_relaxed);
        i.store(2, std::memory_order_relaxed);
        ptr.store(new int{0}, std::memory_order_release);

}

void fun2(){
        while(!ptr.load(std::memory_order_acquire));
        int x = i.load(std::memory_order_relaxed);
}

int main(){
        std::async(std::launch::async, fun1);
        std::async(std::launch::async, fun2);
}
Run Code Online (Sandbox Code Playgroud)

相关问题:在上面的代码中,fun2 是否有可能将原子 i 的值视为 1 或者是否可以保证它会看到值 2?

c++ multithreading c++11 relaxed-atomics

6
推荐指数
1
解决办法
4261
查看次数