Andrea Gulino
Andrea Gulino

Reputation: 55

Max value in an array using OpenMP

I have to solve an exercise about OpenMP; here it is:

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).

For the final calculation I would use

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

My doubt is on how to take advantage of OpenMP to compute the maximum value of A.

The only idea I came up with is using parallel sections to parallelize a recursive maximum computation:

The first call is made with 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;

}

Do you think it is a good solution? Can you tell me if there is any better solution / alternative ?

Upvotes: 2

Views: 10288

Answers (1)

Harald
Harald

Reputation: 3180

What about using a reduction clause to calculate the maximum value within A in the range between [i,j] instead of using recursive calculation?

Something like

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

Upvotes: 2

Related Questions