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

Jon*_*ove 5 c++ multithreading c++-standard-library c++17

关于新的C ++ 17并行算法如何管理线程有很好的参考吗?aka什么时候创建多少线程?是否为每个呼叫创建/销毁它们?

我想答案取决于所使用的编译器。因此,我对gcc的实现特别感兴趣。

Fed*_*dor 0

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

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 );
}
Run Code Online (Sandbox Code Playgroud)

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:
Run Code Online (Sandbox Code Playgroud)

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