問題描述
我想知道是否有一種簡單直接的方法可以在 C++ 中并行計算諸如 for
和基于范圍的 for
循環(huán)之類的循環(huán).你會如何實施這樣的事情?我從 Scala 知道 map
、filter
和 foreach
函數(shù),也許也可以并行執(zhí)行這些函數(shù)?有沒有一種簡單的方法可以在 C++ 中實現(xiàn)這一點?
I wonder if there is a light, straight forward way to have loops such as for
and range based-for
loops compute in parallel in C++. How would you implement such a thing? From Scala I know the map
, filter
and foreach
functions and maybe it would also be possible to perform these in parallel? Is there an easy way to achieve this in C++?
我的主要平臺是 Linux,但如果它可以跨平臺工作就好了.
My primary platform is Linux, but it would be nice if it worked cross-platform.
推薦答案
借助 C++17 中的并行算法,我們現(xiàn)在可以使用:
With the parallel algorithms in C++17 we can now use:
std::vector<std::string> foo;
std::for_each(
std::execution::par_unseq,
foo.begin(),
foo.end(),
[](auto&& item)
{
//do stuff with item
});
并行計算循環(huán).第一個參數(shù)指定執(zhí)行策略
to compute loops in parallel. The first parameter specifies the execution policy
這篇關(guān)于C++ 中的并行循環(huán)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!