我正在阅读
http://en.cppreference.com/w/cpp/thread/condition_variable上的std :: condition_variable,我不明白这一点:
Even if the shared variable is atomic,it must be modified under the
mutex in order to correctly publish the modification to the waiting
thread.
如果未在互斥锁下修改共享原子变量,为什么没有正确发布?怎么理解这个说法?
在另一个页面http://en.cppreference.com/w/cpp/atomic/atomic,有一个声明似乎与第一个声明相矛盾:
If one thread writes to an atomic object while another thread reads
from it,the behavior is well-defined (see memory model for details on
data races)
解决方法
考虑这个例子:
std::atomic_bool proceed(false); std::mutex m; std::condition_variable cv; std::thread t([&m,&cv,&proceed]() { { std::unique_lock<std::mutex> l(m); while(!proceed) { hardWork(); cv.wait(l); } } }); proceed = true; cv.notify_one(); t.join();
这里原子共享数据的继续被修改而不使用互斥,之后通知被发送到条件变量.但是有可能在发送通知的那一刻,线程t没有等待cv:而是在hardWork()内部已经检查过,然后发现它是假的.通知错过了.当t完成hardWork时,它将恢复等待(大概是永远的).
如果主线程在修改共享数据之前锁定了互斥锁,则可以避免这种情况.
我认为这是在说“即使共享变量是原子的,也必须在互斥锁下进行修改才能正确地将修改发布到等待线程”.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。