条件变量
我注意到,当我对条件变量执行等待操作时,它会立即返回。结果是,当执行以下虚拟代码时,循环中使用了 100% 的 CPU :
int main(void) {
boost::condition_variable cond;
boost::mutex mut;
bool data_ready = false;
boost::unique_lock<boost::mutex> lock(mut);
while (!data_ready) {
cond.wait(lock);
}
return 1;
}
我希望调用 cond.wait(lock)
将线程置于声明它不消耗任何 CPU,但事实并非如此。
那么问题出在哪里呢?我从 boost 文档中获取了上面的代码。
(我使用的是 boost 1.44)
谢谢,
纪尧姆
I noticed that when I'm performing a wait operation on a condition variable, it immediately returns. The consequence is that, when executing the following dummy code, 100% of one CPU is being used in the loop :
int main(void) {
boost::condition_variable cond;
boost::mutex mut;
bool data_ready = false;
boost::unique_lock<boost::mutex> lock(mut);
while (!data_ready) {
cond.wait(lock);
}
return 1;
}
I would expect the call to cond.wait(lock)
to put the thread in a state where it's not consuming any CPU but that's not the case.
So where's the problem ? I took the above code from the boost documentation.
(I'm using boost 1.44)
Thanks,
Guillaume
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
condition_variable::wait
可能会虚假返回。也就是说,在没有通知的情况下。它虚假返回的频率是实施质量的问题。在我的机器上,我获取了您的代码,将其更改为使用 std::condition_variable (C++11 中的新功能),然后运行它。它挂起,没有使用 cpu。
听起来像是您平台上的 boost 实现(boost 对于 Windows 和 pthreads 有不同的实现),虚假地唤醒自身以尝试确保它不会错过通知。
A
condition_variable::wait
may return spuriously. That is, without being notified. How often it returns spuriously is a matter of quality of implementation.On my machine, I took your code, changed it to use std::condition_variable (new in C++11), and ran it. It hung with no cpu being used.
It sounds like the boost implementation, on your platform (boost has different implementations for windows and pthreads), spuriously wakes itself to try to ensure that it doesn't miss a notification.
由于程序中没有其他线程,因此线程库立即从 pthread_cond_wait() 返回是非常明智的,否则您的程序将永远休眠。
Since there is no other threads in program, it's pretty sane for threads library to return immediately from pthread_cond_wait() or your program will sleep forever.