Friday, December 24, 2004

Condition variable spurious wakeup

Weiqi's year end review mentioned his spurious wakeup blog entry that he wrote in April. Jonathan and I were talking about this a few weeks back. I was reviewing his code and commented on the importance of checking your condition when you wakeup because of spurious wakeups. So if you are using ACE condition variable you need to make sure you do something like:

ACE_Guard<ACE_Thread_Mutex> guard(mutex_);
while (value != expected_value)
condition_.wait();

The cool thing is that boost's condition variable wait() method takes a predicate functor to handle spurious wakeup.

struct CompareVariable {
bool operator()() const {
return value_ != expected_value_;
}
int value_, expected_value_;
} pred;

boost::mutex::scoped_lock guard(mutex_);
condition.wait(guard, pred);

The
   condition.wait(guard, pred);
above is equivalent to
   while (!pred())wait(lock);

No comments: