C++ openmp 并行 for 循环有两个或多个减少
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9388167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
openmp parallel for loop with two or more reductions
提问by pyCthon
Hi just wondering if this is the right way to go going about having a regular for loop but with two reductions , is this the right approach below? Would this work with more then two reductions as well. Is there a better way to do this? also is there any chance to integrate this with an MPI_ALLREDUCE command?
嗨,只是想知道这是否是进行常规 for 循环但有两次减少的正确方法,这是下面的正确方法吗?这是否也适用于两次以上的减少。有一个更好的方法吗?还有机会将它与 MPI_ALLREDUCE 命令集成吗?
heres the psuedo code
#pragma omp parallel for \
default(shared) private(i) \
//todo first reduction(+:sum)
//todo second reduction(+:result)
for loop i < n; i ++; {
y = fun(x,z,i)
sum += fun2(y,x)
result += fun3(y,z)
}
回答by devil
You can do reduction by specifying more than one variable separated by a comma, i.e. a list:
您可以通过指定多个以逗号分隔的变量来进行归约,即一个列表:
#pragma omp parallel for default(shared) reduction(+:sum,result) ...
#pragma omp parallel for default(shared) reduction(+:sum,result) ...
Private thread variables will be created for sum
and result
that will be combined using +
and assigned to the original global variables at the end of the thread block.
私有线程变量将被创建,sum
并将在线程块末尾result
使用+
并分配给原始全局变量。
Also, variable y
should be marked private.
此外,变量y
应标记为私有。
回答by Azmisov
You can simply add another reduction
clause:
您可以简单地添加另一个reduction
子句:
#include <iostream>
#include <cmath>
int main(){
double sum_i = 0, max_i = -1;
#pragma omp parallel for reduction(+:sum_i) reduction(max:max_i)
for (int i=0; i<5000; i++){
sum_i += i;
if (i > max_i)
max_i = i;
}
std::cout << "Sum = " << sum_i << std::endl;
std::cout << "Max = " << max_i << std::endl;
return 0;
}
From OpenMP 4.5 Complete Specifications (Nov 2015)
来自OpenMP 4.5 完整规范(2015 年 11 月)
Any number of reduction clauses can be specified on the directive, but a list item can appear only once in the reduction clauses for that directive.
可以在指令上指定任意数量的归约子句,但列表项在该指令的归约子句中只能出现一次。
The same works on Visual C++ that uses oMP v2.0: reduction VC++
同样适用于使用 oMP v2.0 的 Visual C++:reduction VC++