Published on

Boost.Thread: `thread_group`

Authors

When you want to handle multiple threads at the same time with Boost.Thread, you can use thread_group like this.

#include <boost/thread.hpp>

void print_and_sleep()
{
  std::cout << "Hello world!" << std::endl;
  boost::this_thread::sleep(boost::posix_time::milliseconds(3000));
}

int main() {

  boost::thread_group tg;
  for (int i = 0; i < 3; i++) {
      tg.create_thread(print_and_sleep);
  }
  tg.join_all();

  return 0;
}

There is nothing wrong with the code above, but apparently C++11 does not have thread_group. So, to keep portability and compatibility in mind, I implemented a thread group using vector, in the same spirit as C++11.

Since thread is a noncopyable class, it cannot be copied. I first wanted to implement it using move semantics, but it would not compile with VC2008, so I ended up storing the threads in shared_ptr and reusing them that way.

#include <boost/smart_ptr/make_shared.hpp>
#include <boost/thread.hpp>

void print_and_sleep()
{
    std::cout << "Hello world!" << std::endl;
    boost::this_thread::sleep(boost::posix_time::milliseconds(3000));
}

void do_join(boost::shared_ptr<boost::thread>& t)
{
    t->join();
}

void join_all(std::vector<boost::shared_ptr<boost::thread> >& vec)
{
    std::for_each(vec.begin(), vec.end(), do_join);
}

int main() {

  typedef std::vector<boost::shared_ptr<boost::thread> > thread_vector;

  thread_vector tv(3);
  for (int i = 0; i < 3; i++) {
      tv[i] = boost::make_shared<boost::thread>(print_and_sleep);
  }
  join_all(tv);

  return 0;
}

Reference:

http://www.justsoftwaresolutions.co.uk/threading/managing_threads_with_a_vector.html