可能很蠢,但与其被问到,不如后悔一辈子。
std::atomic::load
和std::atomic::store
的标准模式是
像这样的东西
注意:假设在下面的all示例中,
data
的初始值为0
作者:
data = 42;
sync_after_write.store(1, memory_order_release);
读者:
while (sync_after_write.load(memory_order_acquire) != 1) {}
assert(data == 42); // must hold
我想知道是否有一种方法可以表达在存储数据值之前发生同步的反转模式。这个想法是为了确保作者还没有开始 修改数据,读者仍然保留其原始值。
沿着这些思路
作者:
sync_before_write.store(1, /* which memory access ? */); // we want to prevent subsequent
// stores to appear before this statement
data = 42;
读者:
data_copy = data;
if (sync_before_write.load(/* which memory access ? */) == 0) { // we want to prevent previous
// loads to appear after this statement
assert(data_copy == 0); // in other words since sync_before_write is zero then
// the writer hasn't started modifying the data value
// yet and it stays to be zero (original)
}
为了简化你的问题,你有一个线程
sync = 1;
data = 42;
...还有另一个线程
data_copy = data;
if (sync == 0)
assert(data_copy == 0);
std::memory_order::seq_cst
),因为sync
和data
之间没有依赖关系。
但是,您希望所有线程都遵守修改顺序,其中 data
在 sync
之后修改。
sync = 1
在data = 42
之前的排序也意味着前者强烈发生在后者之前,这受到顺序一致操作的总顺序的尊重。
获取/释放顺序是不够的,因为虽然在进行修改的线程上
data = 42
无法在sync
之前重新排序,但其他线程可以观察不同的修改顺序。