Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parallelize this array sum using OpenMP?

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

}
like image 249
Tara16 Avatar asked Nov 21 '14 07:11

Tara16


1 Answers

You should use reduction like this:

#pragma omp parallel for reduction (+:sum)
for (int i=0;i<n;i++)
  sum=sum+a[i];
like image 93
Andrey Sozykin Avatar answered Nov 09 '22 00:11

Andrey Sozykin