Reputation: 9343
I have the code as following:
#include <stdio.h>
#include <omp.h>
#define N 10
double x[N];
int main(void)
{
double sum = 0.0;
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < N; ++ i)
x[i] = (double) i;
#pragma omp for reduction(+:sum)
for (int i = 0; i < N; ++ i)
{
sum += (double) x[i];
}
}
printf("%le\n", sum);
return 0;
}
The output is 45, which makes sense. However, if I replace sum += (double) x[i]
with sum = (double) x[i]
, the output is then always 43. Could anyone explain why this happens?
Thanks!
Upvotes: 0
Views: 725
Reputation: 9343
I think I know what's happening here. I thought sum
was copied for each ITERATION, but actually sum
is copied for each THREAD. I have 8 threads running, so one of them has lost its initial value. Solved. Thanks for all your answers here!
Upvotes: 1
Reputation: 6220
If you replace sum += (double) x[i]
by sum = (double) x[i]
, you are not acummulating the result, hence, sum
will store the value of the last iteration.
Upvotes: 3