C++11 Can I ensure a condition_variable.wait() won't miss a notification?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 05:24:14

You should fix this race condition by having thread 2 lock the condition's mutex before changing the flag.

You are describing a typical race condition that happens for unprotected flags and conditions. These race conditions are the reason for the mutex lock pattern in condition usage. Put simply, always have a mutex protect the variables involved in checking a condition value.

In code for thread 2:

unique_lock<mutex> ul(m);
condition = false;
cv.notify_one();

You have a data race because of the conflicting read/write access to condition. This implies that the behavior of your program is not defined.

The race condition on cv is the least of your worries: the program could do anything!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!