C++11 并发读取一个 bool

C++11 reading a bool concurrently

当我有一个 std::condition_variable cond 和一些 bool flag 时,我可以使用谓词等待它:

cond.wait_for(some_lock, std::chrono::milliseconds(100), { return flag; })

现在我想知道:从技术上讲,C++ 在 C++11 中只有一个适当的多线程内存模型,并且在多线程上下文中访问 flag 变量基本上是未定义的。所以我应该声明它 std::atomic<bool> 以逃避未定义的行为,对吗?

我特别想知道:如果我没有声明它 std::atomic,会不会是我一直从 flag 读取过时的值,因为更新从未进入主内存?或者这是 "theoretically yes, but practically never happens" 的情况?

Technically C++ only got a proper multi threaded memory model in C++11, and accessing the flag variable in a multi threaded context is basically undefined.

在 C++ 中访问线程共享变量是明确定义的,只要不存在数据竞争。有关详细信息,请参阅 Threads and data races

... in particular, release of a std::mutex is synchronized-with, and therefore, happens-before acquisition of the same mutex by another thread, which makes it possible to use mutex locks to guard against data races.


互斥lock/unlock构成acquire/release内存屏障。您不需要 std::atomic 用于仅在互斥锁锁定时访问的线程共享状态。当收到条件通知时,它首先锁定互斥量,以便您可以安全地访问共享状态。


当人们尝试将 std::atomic 变量与 std::mutex/std::condition_variable 一起使用并在不持有互斥锁的情况下访问 std::atomic 时,他们经常会引入数据竞争。 .