How to parallelize this array sum using OpenMP?

How can I get this array sum to be parallelized using OpenMP? what should be general and what should be private?

Here is the code for the sum of the array ..

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

}

      

+3


source to share


2 answers


You should use reduction like this:



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

      

+7


source


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

}

      

0


source







All Articles