c++ - openmp parallel for loop with two or more reductions

ID : 274396

viewed : 20

Tags : c++copenmpc++c





Top 3 Answer for c++ - openmp parallel for loop with two or more reductions

vote vote

91

You can do reduction by specifying more than one variable separated by a comma, i.e. a list:

#pragma omp parallel for default(shared) reduction(+:sum,result) ...

Private thread variables will be created for sum and result that will be combined using + and assigned to the original global variables at the end of the thread block.

Also, variable y should be marked private.

See https://computing.llnl.gov/tutorials/openMP/#REDUCTION

vote vote

90

You can simply add another reduction clause:

#include <iostream> #include <cmath>  int main(){     double sum_i = 0, max_i = -1;     #pragma omp parallel for reduction(+:sum_i) reduction(max:max_i)     for (int i=0; i<5000; i++){         sum_i += i;         if (i > max_i)             max_i = i;     }     std::cout << "Sum = " << sum_i << std::endl;     std::cout << "Max = " << max_i << std::endl;     return 0; } 

From OpenMP 4.5 Complete Specifications (Nov 2015)

Any number of reduction clauses can be specified on the directive, but a list item can appear only once in the reduction clauses for that directive.

The same works on Visual C++ that uses oMP v2.0: reduction VC++

vote vote

78

Top 3 video Explaining c++ - openmp parallel for loop with two or more reductions







Related QUESTION?