$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
From: Michael Glassford (glassfordm_at_[hidden])
Date: 2005-01-27 16:49:17
"Cory Nelson" <phrosty_at_[hidden]> wrote in message 
news:9b1d06140501261349f3d6877_at_mail.gmail.com...
> I'm coding a simple thread_pool class, with the help of boost.  I
> wrote a simple test case, and things seem to be out of sync - not 
> all
> the work gets executed.  I think I am using boost::condition wrong,
> can someone take a look?
I see several things:
1) You call this->work_condition.wait(lock) unprotected by a check to 
see if you actually need to wait.
2) You set thread_pool::running to false before the work is finished, 
forcing the thread pool to exit while it still has work queued.
If you want to fix both of these things, you should modify 
thread_pool::worker() something like this:
   void thread_pool::worker() {
      while(true) {
         function_type f;
         {
            boost::mutex::scoped_lock lock(this->work_mutex);
            while (this->work.empty() && this->running)
               this->work_condition.wait(lock);
            if(this->work.empty() && !this->running) break;
            f=this->work.front();
            this->work.pop();
         }
         try {
            f();
         }
         catch(...) {
            // try to keep thread alive..
         }
      }
   }
3) The mutex defined in main() is destroyed while the work objects are 
still referencing and potentially using it.
To fix this, you should declare it before the thread pool so that it 
is destroyed after the thread pool (and all the objects in it) are 
finished. Like this:
   int main(void) {
   try {
      boost::mutex m;
      thread_pool p(2);
      //...
Mike