boost::thread_group in C++11?
Asked Answered
S

3

32

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.

Slacken answered 27/3, 2012 at 17:5 Comment(1)
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).Detachment
P
36

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.

Plummer answered 27/3, 2012 at 17:7 Comment(2)
Since 2012 has there been a better solution to this problem?Potheen
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).Egarton
M
11

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).

Minicam answered 27/1, 2016 at 15:27 Comment(0)
L
0

If you have access to C++20, then you can use std::vector and std::jthread instead of std::thread to create a group of threads.

If you use std::jthread then no need to call join() on each thread. jthread automatically calls join() upon destruction.

Here is a working example:

https://godbolt.org/z/o9rPfd4zn

#include <iostream>
#include <thread>
#include <vector>

int main()
{
    constexpr int count = 3;
    std::vector<std::jthread> thread_group;

    for( int i = 1; i <= count; ++i )
    {
        thread_group.emplace_back([i=i](){ 
            std::this_thread::sleep_for(std::chrono::seconds(i)); 
            std::cout << " Thread " << i << " finished." << std::endl;
            });
    }
    // no need to join the threads here
}
Lian answered 4/3 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.