繁体   English   中英

使用std :: atomic :: compare_exchange_strong时,写入std :: atomic是否可以被其他线程看不到?

[英]Can a write to std::atomic go unseen by other threads while using std::atomic::compare_exchange_strong?

std::atomic<int> g_atomic;

void thread0()
{
  int oldVal = 0;
  int newVal = 1;
  while (g_atomic.compare_exchange_strong(oldVal, newVal, std::memory_order_acq_rel, std::memory_order_acquire))
  {
    // forever counting from 0 to 100 until unexpected value appears
    oldVal = newVal;
    newVal = (oldVal + 1) % 100;
  };
}

void thread1()
{
  // set unexpected value
  g_atomic.store(-1, std::memory_order_release);
}

int main()
{
  g_atomic.store(0);
  std::thread t0(thread0);
  std::thread t1(thread1);
  t0.join();
  t1.join();
  return 0;
}

在thread0中可见之前,是否会在thread0的循环中以某种方式覆盖来自thread1的写入? 然后该程序将永远运行。 这在我的测试中不会发生,但是如果有任何保证说这将永远是这样的话我很感兴趣。

因此,为了提供一个明确的答案,不,thread1永远不会错过来自thread1的写入。

这是因为std::atomic::compare_exchange_strong是一个原子操作,因此thread0的写入要么在此操作开始之前发生(在这种情况下它返回false ),要么在它完成之后(在这种情况下,调用将在下一次循环时失败) )。

如果是其他任何方式, compare_exchange_strong将没有实用程序,不是吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM