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.
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.
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.
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 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).
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
}
© 2022 - 2024 — McMap. All rights reserved.