$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
From: Tobias Schwinger (tschwinger_at_[hidden])
Date: 2007-06-18 15:08:16
Graham Reitz wrote:
> Is there a method  to release all threads waiting on a mutex?  
Yes.
> Or, more 
> generally, a portable way to release a bunch of threads at the same 
> time? 
Try condition::notify_all (see attached code for a sample).
Regards,
Tobias
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>
class runner : boost::noncopyable
{
    boost::condition & go;
    boost::mutex & mutex;
    boost::thread thread;
public:
    explicit runner(boost::condition & go_signal, boost::mutex & m)
      : go(go_signal), mutex(m)
      , thread( boost::bind(& runner::run, this) )
    { }
    ~runner()
    {
        thread.join();
    }
private:
    void run()
    {
        std::cout << std::hex;
        {
          boost::mutex::scoped_lock lock(mutex);
          std::cout << "Runner @ 0x" << (std::ptrdiff_t) this 
              << " ready to run." << std::endl;
          go.wait(lock);
        }
        for (int i = 0; i < 1000; ++i)
        {
          // locking here so the output doesn't get scrambled 
          // and so that non thread-safe iostream variants won't crash
          boost::mutex::scoped_lock lock(mutex);
          std::cout << "Runner @ 0x" << (std::ptrdiff_t) this 
              << " running." << std::endl;
        }
    }
};
int main()
{
  boost::condition go_signal;
  boost::mutex m;
  runner x(go_signal,m);
  runner y(go_signal,m);
  runner z(go_signal,m);
  std::string s;
  std::getline(std::cin, s);
  go_signal.notify_all();
  return 0; 
}