C++11中有类似
boost::thread_group
的东西吗?
我只是尝试将我的程序从使用
boost:thread
移植到 C++11 线程,但无法找到任何等效的东西。
不,C++11 中没有与
boost::thread_group
直接等效的东西。如果您想要的只是一个容器,您可以使用 std::vector<std::thread>
。然后,您可以使用新的 for
语法或 std::for_each
在每个元素上调用 join()
或其他方式。
thread_group
未纳入 C++11、C++14、C++17 或 C++20 标准。
但解决方法很简单:
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();
}
甚至不值得包装在一个类中(但肯定是可能的)。
如果您可以访问 C++20,那么您可以使用 std::jthread 而不是 std::thread。如果您使用
std::jthread
,则无需在每个线程上调用 join()
。 jthread
销毁后会自动调用 join()
。
这是一个工作示例:
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
}