c++ - Can I use OpenMP reduction when the variable is an array element? -
the openmp manual says
a type name in
declare reduction
directive cannot function type, array type, reference type, or type qualifiedconst
,volatile
orrestrict
.
what can produce results array elements? started with:
int main() { // create input array static const int snum = 5000; int input[snum]; for(int i=0; i<snum; ++i){ input[i] = i+1; } // shared output variables reduction int sum[2]; sum[0] = 0; sum[1] = 0; #pragma omp parallel #pragma omp declare reduction(+:sum[0]) #pragma omp declare reduction(+:sum[1]) for(int i=0; i<snum; ++i) { int* p = input+i; if(i%2==0) sum[0] += *p; else sum[1] += *p; } }
this gives compiler error:
27013152.cpp:16:9: error: ‘#pragma’ not allowed here #pragma omp declare reduction(+:sum[0]) ^~~ 27013152.cpp:17:33: error: ‘sum’ not name type #pragma omp declare reduction(+:sum[1]) ^~~ 27013152.cpp:17:36: error: expected ‘:’ before ‘[’ token #pragma omp declare reduction(+:sum[1]) ^
you're mistaking error you're getting. doesn't mean can't reduction on alternating elements. means can't reduction element of array.
that is, can't reduction(+:sum[0])
. can reduction scalar variable , copy element of array afterwards:
void sum_int(const int input[], int num, int *sum) { int sum_even = 0, sum_odd = 0; #pragma omp parallel reduction(+:sum_even) reduction(+:sum_odd) (int = 0; < num; i++) { if (i % 2 == 0) sum_even += input[i]; else sum_odd += input[i]; } sum[0] = sum_even; sum[1] = sum_odd; }
Comments
Post a Comment