有没有关于新的C++17并行算法如何管理线程的好参考资料?也就是说,线程是在何时、以何种方式创建的?它们是为每个调用创建/销毁的吗?
我认为答案取决于所使用的编译器。因此,我特别感兴趣的是它的gcc实现。
有没有关于新的C++17并行算法如何管理线程的好参考资料?也就是说,线程是在何时、以何种方式创建的?它们是为每个调用创建/销毁的吗?
我认为答案取决于所使用的编译器。因此,我特别感兴趣的是它的gcc实现。
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: