受欢迎的博客标签

C++ 17标准中对STL库中的69个算法加入了执行策略(execution policies),允许在少量修改的情形下,对原有STL库算法实现并行计算。它由域名空间algorithm.h来实现。

Step 1:确定编译器强制执行的C++17语言标准

目前主流 vs 2019 16.8 C++编译器已加入对该特性的支持。

项目-》常规-》C++语言标准-》预览 - 最新 C++ 工作草案中的功能 (std:c++latest)

Step 2: 并行代码

 

#include <algorithm>  //for c++17 par_unseq
#include <execution>  //for c++17 std::for_each,std::execution
	std::vector<std::string> foo;
	std::for_each(
		std::execution::par_unseq,
		foo.begin(),
		foo.end(),
		[](auto&& item)
		{
			//do stuff with item
		});

 

std::vector<int> v(10000, 1);

int main()
{
    std::vector<int> v(10000, 1);
    std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
}

With C++17, the most of the algorithms of the Standard Template Library will be available in a parallel version. Therefore, you can invoke an algorithm with a so-called execution policy. This execution policy specifies if the algorithm runs sequential (std::seq), parallel (std::par), or parallel and vectorised (std::par_unseq).

By using the execution policy, you can specify whether the algorithm should run sequential, parallel, or parallel and vectorised.

std::vector<int> vec ={3, 2, 1, 4, 5, 6, 10, 8, 9, 4};

std::sort(vec.begin(), vec.end());                            // sequential as ever
std::sort(std::execution::seq, vec.begin(), vec.end());       // sequential
std::sort(std::execution::par, vec.begin(), vec.end());       // parallel
std::sort(std::execution::par_unseq, vec.begin(), vec.end()); // parallel and vectorized

Therefore, the first and second variations of the sort algorithm run sequential, the third parallel, and the fourth parallel and vectorised.矢量化代码与原子访问

vector<int> v = ...

// standard sequential sort
std::sort(v.begin(), v.end());

// sequential execution
std::sort(std::parallel::seq, v.begin(), v.end());

// permitting parallel execution
std::sort(std::parallel::par, v.begin(), v.end());

// permitting parallel and vectorized execution
std::sort(std::parallel::par_unseq, v.begin(), v.end());

 

Parallel Algorithms of the Standard Template Library

https://www.modernescpp.com/index.php/parallel-algorithm-of-the-standard-template-library

C++17: New Parallel Algorithms of the Standard Template Library

https://www.modernescpp.com/index.php/c-17-new-algorithm-of-the-standard-template-library