Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

multithreading - OpenMP and C++: private variables

I am quite new with OpenMP and c++ and perhaps because of this I am having some really basic problems.

I am trying to do a static schedule with all variables being private (just in case, in order to verify that the result obtained is the same as the non-parallel one).

The problem arises when I see variables such as bodies which I do not know where they came from, as they are not previously defined.

Is it possible to define all the appearing variables, such as bodies, as private? How could that be done

  std::vector<phys_vector> forces(bodies.size());

  size_t i, j; double dist, f, alpha;


  #pragma omp parallel for schedule(static) private(i, j, dist, f, alpha)
  for (i=0; i<bodies.size(); ++i) {
    for (j = i+1; j<bodies.size(); ++j) {
      dist = distance(bodies[i], bodies[j]);
      if (dist > param.min_distance()) {
        f = attraction(bodies[i], bodies[j], param.gravity(), dist);
        alpha = angle(bodies[i],bodies[j]);
        phys_vector deltaf{ f * cos(alpha) , f * sin(alpha) };
        forces[i] += deltaf;
        forces[j] -= deltaf;
      }
    }
  }
  return forces;
}

PS: with the current code, the execution result varies from the non-parallel execution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It should be reiterated that your bodies variable does not just randomly appear out of nowhere; you should find out exactly where it is declared and what it is defined as. However, because you are only accessing elements of bodies and never changing them, this variable should be shared anyway, so is not your problem.

Your actual problem comes from the forces variable. You must ensure that different threads are not changing the variables forces[j] for the same j. If you follow the logic of your loop, you can be ensured that forces[i] is only accessed by the different threads, so there is no contention between them there. But forces[j] for the same j can very easily be modified by different iterations of your parallel i loop. What you need to do is reduce on your array by following one of the answers from that StackOverflow link.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...