0

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.
TNg
  • 856
  • 1
  • 9
  • 15
  • Hi. Thanks for comment. I know reduction can solve the problem. My question is not about solving this problem but about why using firstprivate and lastprivate as above does not work properly. – TNg Sep 08 '17 at 11:15
  • Oh I see the point. Thank Mark! – TNg Sep 08 '17 at 11:32
  • Possible duplicate of [Summing with OpenMP using C](https://stackoverflow.com/questions/7687499/summing-with-openmp-using-c) – Jorge Bellon Sep 08 '17 at 12:09
  • Yes I think you are right. It might not be exactly a duplicate but the answers are already there and the question is not completely clear. At the very least, an edit would be necessary. – Jorge Bellon Sep 08 '17 at 14:24
  • The case isn't big enough to benefit from threaded parallel. Even for single thread omp simd reduction omp will not be fully effective. – tim18 Sep 08 '17 at 15:33
  • @tim18: you are undoubtedly right but for pedagogical purposes small jobs have some advantages. – High Performance Mark Sep 08 '17 at 15:47
  • Possible duplicate of [How are firstprivate and lastprivate different than private clauses in OpenMP?](https://stackoverflow.com/questions/15304760/how-are-firstprivate-and-lastprivate-different-than-private-clauses-in-openmp) – High Performance Mark Sep 08 '17 at 15:47
  • Hi all. Thanks for comments. My question is not about solving summing problem using openmp or difference between firstprivate and lastprivate with private.It is about whether using firstprivate and lastprivate as above is correct because I misunderstood lastprivate (so I thought this can solve the summing as reduction but it actually cannot). Posing this specific question absolutely help clear my misunderstanding. And I think this may as well benefit those who already know about firstprivate and lastprivate but probably don't understand them correctly that they need a specific example. – TNg Sep 09 '17 at 01:01

0 Answers0