OpenMP和C ++:私有变量 [英] OpenMP and C++: private variables
问题描述
我对OpenMP和c ++很新,也许因为这样我有一些真正的基本问题。
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).
当我看到变量 body
,我不知道他们来自哪里,因为他们以前没有定义。
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.
将所有出现的变量,如 bodies
定义为private?
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:对于当前代码,执行结果不同于非并行执行。
PS: with the current code, the execution result varies from the non-parallel execution.
推荐答案
应该重申, bodies
只是随机出现在无处;你应该准确地知道它被声明的位置和它被定义为。但是,因为你只能访问 body
的元素并且从不改变它们,所以这个变量应该是 shared
不是您的问题。
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.
您的实际问题来自 force
变量。您必须确保不同的线程不会改变相同 j
的变量 forces [j]
。如果你遵循循环的逻辑,你可以确保 forces [i]
只被不同的线程访问,所以它们之间没有争用。但对于相同的
循环。您需要做的是在阵列上减少,方法是按照下面的一个答案StackOverflow链接。 j
, force [j]
可以很容易地通过不同的迭代修改< c> i
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.
这篇关于OpenMP和C ++:私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!