30

Is there anything like boost::thread_group in C++11?

I'm just trying to port my program from using boost:thread to C++11 threads and wasn't able to find anything equivalent.

AbuBakr
  • 968
  • 2
  • 11
  • 22
  • 4
    Boost threads and C++11 threads are different. I personally keep using boost threads because of the more complete API (and the lack of current implementation of eg. thread local storage). – Alexandre C. Mar 27 '12 at 17:07

2 Answers2

35

No, there's nothing directly equivalent to boost::thread_group in C++11. You could use a std::vector<std::thread> if all you want is a container. You can then use either the new for syntax or std::for_each to call join() on each element, or whatever.

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
  • 4
    Since 2012 has there been a better solution to this problem? – pyCthon Aug 31 '13 at 20:58
  • 3
    I'd like to add that there is really no magic in `boost::thread_group`, it's a little more than a vector of threads (the "little more" being some utility functions like `join_all` and `create_thread`). – Tamás Szelei Jan 17 '16 at 13:45
9

thread_group didn't make it into C++11, C++14, C++17 or C++20 standards.

But a workaround is simple:

  std::vector<std::thread> grp;

  // to create threads
  grp.emplace_back(functor); // pass in the argument of std::thread()

  void join_all() {
    for (auto& thread : grp)
        thread.join();
  }

Not even worth wrapping in a class (but is certainly possible).

rustyx
  • 80,671
  • 25
  • 200
  • 267