C++17 并行运算指南:执行策略、算法与实战
C++17 引入了一些新的并行运算特性,其中最明显的是 <execution> 头文件中的三种执行策略:
std::execution::seq:顺序执行策略,即串行执行。std::execution::par:并行执行策略,使用系统支持的所有线程进行并行计算。std::execution::par_unseq:混合执行策略,使用所有线程进行并行计算,并且允许非确定性的乱序执行。
这些执行策略可以用于许多适用的算法中,比如 std::transform、std::for_each、std::sort 等等。例如,可以使用如下代码并行计算一个向量的平方和:
#include <iostream>
#include <vector>
#include <numeric>
#include <execution>
int main()
{
std::vector<int> v(10000, 1);
int sum = std::transform_reduce(
std::execution::par, v.begin(), v.end(), 0,
[](int x, int y) { return x + y * y; },
[](int x, int y) { return x + y; }
);
std::cout << "The sum of squares is " << sum << std::endl;
return 0;
}
这段代码使用 std::transform_reduce 算法计算向量 v 中所有元素的平方和,并使用 std::execution::par 执行策略实现并行计算。在实际运行中,这个算法会使用系统支持的所有线程进行并行计算,从而提高计算效率。
除了执行策略,C++17 还引入了一些新的并行算法,比如 std::reduce、std::exclusive_scan、std::inclusive_scan 等等。这些算法可以更方便地实现并行计算,并且可以与执行策略一起使用,以实现更高效的计算。
原文地址: https://www.cveoy.top/t/topic/nmE8 著作权归作者所有。请勿转载和采集!