Condition variables
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;开发者_StackOverflow中文版
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
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.
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.
精彩评论