4

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Guillaume
  • 43
  • 2

2 Answers2

3

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.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • the "spurious" event is a one in a every saturn aligns with jupiter case. This is worth mentioning but it should not be used to justify this case. spurious wakes up can be excpected to happen when a system exception (sigbus or some signal) is raised for example. This won't happen all the time, he has an other issue. – v.oddou Mar 24 '14 at 02:28
1

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.

blaze
  • 4,326
  • 18
  • 23