9

How can I make this array sum is parallelized using OpenMP ? what should be shared, and what should be private ?

Here is the code for array sum ..

main()         
{        
    int a[10], i, n, sum=0;    

    printf("enter no. of elements");
    scanf("%d",&n); 
    printf("enter the elements");   

    for(i=0;i<n;i++)    
        scanf("%d",&a[i]);

    for (i=0;i<n;i++)
        sum=sum+a[i];

    for(i=0;i<n;i++)
        printf("\n a[%d] = %d", i, a[i]);

    printf("\n sum = %d",sum);

}

2 Answers 2

26

You should use reduction like this:

#pragma omp parallel for reduction (+:sum)
for (int i=0;i<n;i++)
  sum=sum+a[i];
Sign up to request clarification or add additional context in comments.

1 Comment

Given that i is defined elsewhere, shouldn't it be marked as private to avoid race conditions?
-2

check out this code.

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
void main()
{
    int sum=0;
    int lsum=0;
    int A[8]={1,2,3,4,5,6,7,8};

    #pragma omp parallel private(lsum)
    {
        int i;
        #pragma omp for
            for (i=0; i<8; i++)
            {
                lsum = lsum +A[i];
            }
        #pragma omp critical
            {
            sum+=lsum;
            }
    }
    printf("%d/n", sum);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.