I compute the sum from 0 to N = 100 using openmp. Specifically, I use for directive
with firstprivate
and lastprivate
keys to obtain the the value of s
from the last iteration at each thread and sum it up. The logic seems right but this code sums up to 1122 while the correct result is 4950. Does anyone know why?
Thanks.
#define N 100
int main(){
int s = 0;
int i;
#pragma omp parallel num_threads(8) //shared(s) private(i)
{
// s = 0;
#pragma omp for firstprivate(s) lastprivate(s)
for(i=0; i<N; i++)
s += i;
}
printf("sum = %d\n",s);
return 1;
}
- Edit: I don't think my question is a duplicate of this question. That question is the difference between firstprivate and lastprivate with private while in my case I don't have such problem. My question is about whether the use of lastprivate and firstprivate in this very specific example is proper. I think this question can benefit some people who have misunderstood lastprivate as I did.