int v[10] = {2,9,1,3,5,7,1,2,0,0};
int maximo = 0;
int b = 0;
int i;
#pragma omp parallel for shared(v) private(i) reduction(max:maximo)
for(i = 0; i< 10; i++){
if (v[i] > maximo)
maximo = v[i];
b = i + 100;
}
当 maximo 获得其最大值时,如何获得 b 在迭代过程中获得的值(以及 for 循环后的值)?
最佳答案
TL;DR 您可以使用User-Defined Reduction .
首先,而不是:
for(i = 0; i< 10; i++){
if (v[i] > maximo)
maximo = v[i];
b = i + 100;
}
你的意思是:
for(i = 0; i< 10; i++){
if (v[i] > maximo){
maximo = v[i];
b = i + 100;
}
}
OpenMP 具有考虑单个目标值的内置缩减函数,但是在您的情况下,您希望考虑 max
和数组索引这两个值来缩减。之后OpenMP 4.0人们可以创建自己的归约函数(即,User-Defined Reduction)。
首先,创建一个结构体来存储两个相关值:
struct MyMax {
int max;
int index;
};
然后我们需要教导 OpenMP 实现如何减少它:
#pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)
我们相应地设置并行区域:
#pragma omp parallel for reduction(maximo:myMaxStruct)
for(int i = 0; i< 10; i++){
if (v[i] > myMaxStruct.max){
myMaxStruct.max = v[i];
myMaxStruct.index = i + 100;
}
}
旁注您实际上并不需要private(i)
,因为使用#pragma omp parallel for
<的索引变量em>for 循环无论如何都会隐式私有(private)。
全部放在一起:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
struct MyMax {
int max;
int index;
};
int main(void)
{
#pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)
struct MyMax myMaxStruct;
myMaxStruct.max = 0;
myMaxStruct.index = 0;
int v[10] = {2,9,1,3,5,7,1,2,0,0};
#pragma omp parallel for reduction(maximo:myMaxStruct)
for(int i = 0; i< 10; i++){
if (v[i] > myMaxStruct.max){
myMaxStruct.max = v[i];
myMaxStruct.index = i + 100;
}
}
printf("Max %d : Index %d\n", myMaxStruct.max, myMaxStruct.index);
}
输出:
Max 9 : Index 101
(索引为 101,因为 b = i + 100)
关于c - 减少最大值并保存其索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66664531/