【发布时间】:2017-02-27 13:20:19
【问题描述】:
我想了解 C++ 中内存屏障的工作原理。 例如,我在这种情况下使用 std::atomic:
#include <iostream>
#include <atomic>
int main()
{
std::atomic<int> a;
int n = load();//returns 1 or other value written by other thread
a.store (n, std::memory_order_release);
}
上面的代码在语义上是否与下面的代码相同?
#include <iostream>
#include <atomic>
int main()
{
std::atomic<int> a;
int n = load();
std::atomic_thread_fence(std::memory_order_release);
n = 100;//assume assignment is atomic
}
如果我是对的,我能否确定所有可以接受内存屏障作为参数的 C++ 函数的行为都是相同的?
【问题讨论】:
-
你的意思是在 main 函数的第二行,在两个例子中
int n = a.load(std::memory_order_acquire)和在第二个例子中,第四行:a=100? -
不,加载函数不是 std::atomic 加载函数。这是一个用户实现的函数,它返回一些数据
-
这个例子看起来很混乱。第一个摘录清楚地将一个值存储到
a中。但是第二个摘录根本没有引用a,那为什么会出现呢?
标签: c++ multithreading memory-barriers