Is it possible to do a reduction on an array with openmp?

前端 未结 5 654
一整个雨季
一整个雨季 2020-12-15 05:57

Does OpenMP natively support reduction of a variable that represents an array?

This would work something like the following...

float* a = (float*) c         


        
5条回答
  •  执笔经年
    2020-12-15 06:40

    Array reduction is now possible with OpenMP 4.5 for C and C++. Here's an example:

    #include 
    
    int main()
    {
    
      int myArray[6] = {};
    
      #pragma omp parallel for reduction(+:myArray[:6])
      for (int i=0; i<50; ++i)
      {
        double a = 2.0; // Or something non-trivial justifying the parallelism...
        for (int n = 0; n<6; ++n)
        {
          myArray[n] += a;
        }
      }
      // Print the array elements to see them summed   
      for (int n = 0; n<6; ++n)
      {
        std::cout << myArray[n] << " " << std::endl;
      } 
    }
    

    Outputs:

    100
    100
    100
    100
    100
    100
    

    I compiled this with GCC 6.2. You can see which common compiler versions support the OpenMP 4.5 features here: https://www.openmp.org/resources/openmp-compilers-tools/

    Note from the comments above that while this is convenient syntax, it may invoke a lot of overheads from creating copies of each array section for each thread.

提交回复
热议问题