问题
I have the following code:
void simulation (MD *md){
double sum;
#pragma omp parallel private (move)
{
for(move = 0; move < maxIterations; ++move)
{
cicleDoMove(md);
cicleForces(md);
cicleMkekin(md,sum);
// ...
}
}
}
where :
void cicleMkekin(Md *md, double sum){
#pragma omp for reduction(+ : sum)
for (i = 0; i < md->mdsize; i++)
{
sum += mkekin(..);
}
// ..
}
I got the following error:
"reduction variable 'sum' is private in outer context"
The variable sum is shared not private, in fact if I change the simulation code to:
void simulation (MD *md){
double sum;
#pragma omp parallel private (move)
{
for(move = 0; move < maxIterations; ++move)
{
cicleDoMove(md);
cicleForces(md);
#pragma omp for reduction(+ : sum)
for (i = 0; i < md->mdsize; i++)
{
sum += mkekin(..);
}
// ...
}
}
}
it works perfectly.
Is there anyway I can used my first code version without getting that error? or am I doing something wrong?
回答1:
OpenMP can be a bit confusing in this particular case. The specification prescribes (§2.14.3.6) that:
A list item that appears in a reduction clause of a worksharing construct must be shared in the parallel regions to which any of the worksharing regions arising from the worksharing construct bind.
Furthermore it says (§2.14.1.1), for C and C++, that
Variables with automatic storage duration that are declared in a scope inside the construct are private.
In your case, the variable sum
is declared in the scope for invocations of the function cicleMkekin
and, as a function parameter, has automatic storage duration. Hence, when you call cicleMkekin
from within your parallel region (or, for that matter, from the implicit top-level parallel region that coincides with the execution of your program), sum
is considered to be a private variable. As a result, your reduction clause is indeed illegal and the error message you are getting is, confusing as it may be, in fact spot on.
In the version of your code in which you have manually inlined the call to cicleMkekin
, you declare the variable sum
outside of the parallel region. Such a variable, in absence of a default
clause or a so-called explicitly determined data-sharing attribute for that variable, are indeed shared (§2.14.1) and, so, the reduction
clause in that version of your code is legal.
来源:https://stackoverflow.com/questions/27253691/reduction-variable-is-private-in-outer-context