首页 > 解决方案 > 混淆发生在并发关系之前

问题描述

下面是Concurrency in Action中给出的示例,作者说assert可能会触发,但我不明白为什么。

#include <atomic>
#include <thread>
#include <assert.h>
std::atomic<bool> x,y;
std::atomic<int> z;
void write_x_then_y()
{
  x.store(true,std::memory_order_relaxed);
  y.store(true,std::memory_order_relaxed);
}
void read_y_then_x()
{
  while(!y.load(std::memory_order_relaxed));
  if(x.load(std::memory_order_relaxed))
  ++z;
}
int main()
{
  x=false;
  y=false;
  z=0;
  std::thread a(write_x_then_y);
  std::thread b(read_y_then_x);
  a.join();
  b.join();
  assert(z.load()!=0);
}

据我所知,在每个单线程中,sequenced before也意味着happens before. 因此,在线程 a 中,存储x发生在之前y,这意味着x应该在之前进行修改,y并且结果x.store应该在修改之前可见y

但是在这个例子中,作者说 和 之间的商店x可以y重新排序,为什么?这是否违反sequenced beforeand的规则happens before

标签: c++concurrencymemory-barriersmemory-modelstdatomic

解决方案


推荐阅读