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

6

有没有关于新的C++17并行算法如何管理线程的好参考资料?也就是说,线程是在何时、以何种方式创建的?它们是为每个调用创建/销毁的吗?

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


libstdc++曾经被提供给英特尔的实现,但目前不清楚其状态如何。 - Rakete1111
无法确定创建多少个线程,至少应该取决于std::hardware_concurrency(),它返回您可以使用的实际硬件线程数。但是,是的,它们在每次调用时都会被创建和销毁。 - Eduard Rostomyan
1个回答

0

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个线程之后,它们会在接下来的并行算法中继续被重复使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接