在C ++中的并行循环 [英] Parallel Loops in C++
问题描述
我想知道是否有一种简单明了的方法来计算循环,例如for循环和基于循环的C ++并行循环。你将如何执行这样的事情?从斯卡拉我知道地图,过滤器和foreach函数也许它也可能执行这些并行?有没有一种简单的方法来在C ++中实现这一点。
我的主要平台是Linux,但是如果它能够跨平台的话,它将会很好。
?您可以查看 OpenMP ,尽管它不是C ++的一部分。但它被编译器广泛支持。
至于基于范围的循环,请参阅使用OpenMP与C ++ 11基于范围的for循环?。
我还在 http://www.open-std.org 上看到了一些文件,表明了将并行结构/算法并入到未来的C ++中的一些努力,但不知道他们目前的状态如何。
UPDATE
只需添加一些示例代码即可:
template< typename RAIter>
void loop_in_parallel(RAIter first,RAIter last){
const size_t n = std :: distance(first,last);
#pragma omp parallel for
for(size_t i = 0; i auto& elem = *(first + i);
//用elem
线程数可以在运行时通过 OMP_NUM_THREADS
环境变量设置。
I wonder if there is a light, straight forward way to compute loops such as for and range based for loops in parallel in C++. How would you implement such a thing? From Scala I know the map, filter and foreach functions maybe it would also possible to perform these parallel? Is there an easy way to achieve this in C++. My primary plattform is Linux but it would be nice if it works cross-plattform.
What is your platform? You can look at OpenMP, though it's not a part of C++. But it is widely supported by compilers.
As for range-based for loops, see, e.g., Using OpenMP with C++11 range-based for loops?.
I've also seen few documents at http://www.open-std.org that indicate some efforts to incorporate parallel constructs/algorithms into future C++, but don't know what's their current status.
UPDATE
Just adding some exemplary code:
template <typename RAIter>
void loop_in_parallel(RAIter first, RAIter last) {
const size_t n = std::distance(first, last);
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
auto& elem = *(first + i);
// do whatever you want with elem
}
}
The number of threads can be set at runtime via the OMP_NUM_THREADS
environment variable.
这篇关于在C ++中的并行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!