Boost logo

Boost :

Subject: [boost] [threads] API Design Question
From: Alexander Bernauer (alex_at_[hidden])
Date: 2009-02-04 09:28:50


Hello

Why is it, that the wait and timed_wait functions of the
condition_variable class do not encapsulate the problem of spurious
wakeups?

I wonder whether there are good reasons. I have seen libraries which do
so. Do they miss a corner case?

For illustration here is a sketch of a wrapper class
---8<---
class save_condition_variable {
public:
   save_condition_variable() : waiting(0), wakeup(0) { }

   void notify_one()
   {
      if (wakeup < waiting) {
          ++wakeup;
      }
      cond.notify_one();
   }

   void notify_all()
   {
      wakeup = waiting;
      cond.notify_all();
   }

   void wait(unique_lock<mutex>& lock)
   {
      ++waiting;
      do { cond.wait(lock) } while (wakeup==0);
      --waiting;
      --wakeup;
   }

   bool timed_wait(unique_lock<mutex>& lock, system_time const& abs_time)
   {
      ++waiting;
      bool res = true;
      while(wakeup==0 and res) {
         res = cond.timed_wait(lock, abs_time);
      }
      --waiting;
      if (res) --wakeup;
      return res;
   }

private:
   condition_variable cond;
   int waiting;
   int wakeup;
};
--->8---

Having the spurious wakeup problem handled by the library is a
significant increase of comfort for both developers and maintainers.

regards

Alex


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk