How to parallelize this array sum using OpenMP?

前端 未结 2 957
忘掉有多难
忘掉有多难 2020-12-11 05:33

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

m         


        
相关标签:
2条回答
  • 2020-12-11 06:12

    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);
    
    }
    
    0 讨论(0)
  • 2020-12-11 06:28

    You should use reduction like this:

    #pragma omp parallel for reduction (+:sum)
    for (i=0;i<n;i++)
      sum=sum+a[i];
    
    0 讨论(0)
提交回复
热议问题