【问题标题】:How are threads managed in the new C++17 parallel algorithms?新的 C++17 并行算法中的线程是如何管理的?
【发布时间】:2018-11-11 13:25:39
【问题描述】:

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

我认为答案取决于使用的编译器。所以我会对它的 gcc 实现特别感兴趣。

【问题讨论】:

  • libstdc++ 提供了 Intel 的实现,但不知道现在是什么状态。
  • 无法固定创建多少线程,它至少应该取决于std::hardware_concurrency(),它返回您可以使用的实际硬件线程数。但是,是的,它们在每次调用时都会被创建和销毁。

标签: c++ multithreading c++17 c++-standard-library


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多