簡體   English   中英

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

[英]How are threads managed in the new C++17 parallel algorithms?

是否有關於新的 C++17 並行算法如何管理線程的很好的參考? 又名何時以及創建了多少線程? 它們是否為每次調用創建/銷毀?

我認為答案取決於使用的編譯器。 所以我會對它的 gcc 實現特別感興趣。

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 );
}

每次從另一個線程調用比較器時都會打印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 個線程后,它們將繼續在以下並行算法中重用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM