8
votes

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

2 Answers

20
votes

You should use reduction like this:

#pragma omp parallel for reduction (+:sum)
for (i=0;i<n;i++)
  sum=sum+a[i];
-1
votes

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

}