跳转至

并行STL

引言

在用for_each遍历集合中的每个元素时,我们对每个元素都做一次处理,这个过程是单线程的。

#include <iostream>
#include <algorithm>

void process(const int& item) {
    //对item做处理
    //...
    std::cout << item << std::endl;
}

int arr[10] = {0, 1,2,3,4,5,6,7,8,9};
std::for_each(arr, arr+10, process);

在C++17以后,可以传入一个并行策略,让算法库帮我们做并行处理,但是对于数据竞争需要用户自行处理。

#include <execution>

std::for_each(
    std::execution::par,  //并行策略
    arr, arr+10000, process
);

三种并行策略

并行策略 说明
std::execution::seq 调用者线程单线程方式,以不确定的顺序访问元素
std::execution::par 多线程(由库隐式的创建线程)方式,在每个线程中,以不确定的顺序访问元素
std::execution::par_unseq multiple threads and may be vectorized - calls are unsequenced with respect to each other and possibly interleaved