GCC 通过 Intel Threading Building Blocks (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 thread\n"; }
};
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 个线程之后,它们会继续在以下并行算法中重复使用。