【发布时间】:2018-05-11 06:30:23
【问题描述】:
在 C++ 内存模型中,所有顺序一致的操作的所有加载和存储都有一个总顺序。我想知道这如何与具有其他内存顺序的操作交互,这些内存顺序在顺序一致的加载之前/之后进行排序。
例如,考虑两个线程:
std::atomic<int> a(0);
std::atomic<int> b(0);
std::atomic<int> c(0);
//////////////
// Thread T1
//////////////
// Signal that we've started running.
a.store(1, std::memory_order_relaxed);
// If T2's store to b occurs before our load below in the total
// order on sequentially consistent operations, set flag c.
if (b.load(std::memory_order_seq_cst) == 1) {
c.store(1, std::memory_order_relaxed)
}
//////////////
// Thread T2
//////////////
// Blindly write to b.
b.store(1, std::memory_order_seq_cst)
// Has T1 set c? If so, then we know our store to b occurred before T1's load
// in the total order on sequentially consistent operations.
if (c.load(1, std::memory_order_relaxed)) {
// But is this guaranteed to be visible yet?
assert(a.load(1, std::memory_order_relaxed) == 1);
}
是否保证T2中的断言不会触发?
我在这里寻找标准的详细引用。特别是我认为这需要显示从 T1 中的 b 的负载 与 存储同步到 T2 中的 b 以便确定存储到 a 线程间发生在从 a 加载之前,但据我所知,标准说 memory_order_seq_cst 存储与加载同步,但不是相反。
【问题讨论】:
标签: c++ language-lawyer atomic memory-model stdatomic