这个程序是
std::condition_variable cond_var;
std::mutex mtx;
std::atomic<int> value {0};
const auto mem_ord = std::memory_order_seq_cst;
std::thread notify_thread([&]
{
{
//std::unique_lock<std::mutex> lock (mtx);
value.store (1, mem_ord);
}
cond_var.notify ();
});
{
std::unique_lock<std::mutex> lock (mtx);
cond_var.wait (lock, [&] { return value.load (mem_ord) != 0; });
}
notify_thread.join ();
保证终止或可能陷入僵局?如果有人会使用mem_ord = std::memory_order_relaxed
呢?store
进入atomic<int>
. _ cppreference.com要求必须取消注释带有 lock-guard 的行notify_thread
。
我希望(使用任何内存顺序)在通知store
之前发生,在中的(潜在)唤醒wait
之前发生,在load
. (我说“潜在的唤醒”是因为notify-thread
当然可以在条件变量之前完成,wait
在这种情况下永远不会有唤醒)。所以,我会假设(使用任何内存顺序)没有必要取消注释与 lock-guard 的行。