如何在新的 C++17 并行算法中管理线程?



关于新的 C++17 并行算法如何管理其线程,是否有很好的参考?也就是何时创建以及创建多少个线程?它们是否为每个调用创建/销毁?

我认为答案取决于使用的编译器。所以我对海湾合作委员会对它的实施特别感兴趣。

GCC 通过英特尔线程构建模块 (TBB( 库实现 C++17 并行算法: https://solarianprogrammer.com/2019/05/09/cpp-17-stl-parallel-algorithms-gcc-intel-tbb-linux-macos/

TBB 维护一个线程池,而不是每次都重新创建它们。这可以使用这个简单的程序进行验证:

#include <algorithm>
#include <execution>
#include <vector>
#include <iostream>
#include <thread>
struct A {
A() { std::cout << "new threadn"; }
};
thread_local A a;
int main()
{
constexpr int N = 100000;
std::vector<int> v(N);
for ( int i = 0; i < N; ++i )
v[i] = N - i;
auto v1 = v, v2 = v;
auto comparator = [](int l, int r) {
(void)a; // to create thread_local object in new thread
return l < r;
};

std::cout << "Hardware concurrency: " << std::thread::hardware_concurrency() << "n";
std::cout << "First parallel algorithm:n";
std::sort( std::execution::par_unseq, v.begin(), v.end(), comparator );
std::cout << "Second parallel algorithm:n";
std::sort( std::execution::par_unseq, v1.begin(), v1.end(), comparator );
std::cout << "Third parallel algorithm:n";
std::sort( std::execution::par_unseq, v2.begin(), v2.end(), comparator );
}

每次从另一个线程调用比较器时,都会打印new thread

在我的计算机上,它打印了AMD Ryzon 9 3900X处理器,Ubuntu 20.04和GCC 10.3:

$ /usr/bin/g++-10 -std=c++20 par.cpp -ltbb
$ ./a.out
Hardware concurrency: 24
First parallel algorithm:
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
new thread
Second parallel algorithm:
new thread
new thread
Third parallel algorithm:

这意味着在所有 24 个线程创建后,它们将继续在以下并行算法中重用。

最新更新