c - 减少最大值并保存其索引

标签 c multithreading parallel-processing openmp reduction

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;
}

ma​​ximo 获得其最大值时,如何获得 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/

相关文章:

Android:如何以正确的方式使用 Gottox/socket.io-java-client 库?

r - mclapply 但不是 lapply 停止 R

c - 为什么在错误名称前添加连字符

c - 如何从 C 中的套接字读取整数

c - C中的算法比较,有什么区别?

c - 如何解决这个编译警告? (格式说明符问题)

linux - 一种检测哪一侧套接字对等点触发断开连接的方法

java - while(true) 使cpu无法读取共享变量的最新值

parallel-processing - 使用 GNU parallel 并行化具有各种参数的脚本

c# - LINQ - 如果我有很多更改,我应该以某种方式定期 SubmitChanges() 吗?