使用 OpenMP 的数组中的最大值

Max value in an array using OpenMP

我要解决一个关于 OpenMP 的练习;这里是:

Write the OpenMP code (the minimal fragment of code you need) that takes an array A of integers (of size NUM) and fills an array B (of floats) with the values B[i]=A[i]/MaxA (MaxA must be calculated as part of the provided code).

对于最终计算,我将使用

#pragma omp parallel for shared(A,B)
for(int i=0; i<NUM; i++) {
   B[i] = A[i]/MaxA;
}

我的疑惑是如何利用OpenMP来计算A的最大值。

我想到的唯一想法是使用并行部分来并行化递归最大计算:

第一次调用是i=0; j= sizeOfA - 1

int max(int A[], int i, int j) {

    // Leaves conditions
    switch (j-i) {
        case 1:
        {   if( A[i]>A[j] )
                return A[i];
            else
                return A[j];
        }
                break;
        case 0:
            return A[i];
            break;
    }


    int left, right;
    #pragma omp parallel sections
    {
        #pragma omp section
        {
            left = max( A, i, i+(j-i)*0.5);
        }

        #pragma omp section
        {
            right = max( A, i+(j-i)*0.5+1, j);

        }
    }

    // Nodes conditions
    if( right > left )
        return right;
    else
        return left;

}

您认为这是一个好的解决方案吗?你能告诉我是否有更好的解决方案/替代方案吗?

如果不使用递归计算,使用归约子句计算[i,j]之间A内的最大值怎么样?

类似

int max(int A[], int i, int j)
{
    int max_val = A[0];

    #pragma omp parallel for reduction(max:max_val) 
    for (int idx = i; idx < j; idx++)
       max_val = max_val > A[idx] ? max_val : A[idx];

    return max_val;
}