OpenMP outer loop private or shared

情到浓时终转凉″ 提交于 2019-12-02 06:23:16

问题


I have a question about OpenMP. Does it make any difference whether I declare i in the outer loop as private or shared?

int i,j;
#pragma omp parallel for private(j)
for (i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        //do something
    }
}

回答1:


i should be defined as private in your code. As each thread will run a proportion of the i loop, each thread should keep a private i so that the loop body knows which iteration he is in.

However a better way is to define variables when you use them, so that you don't need to specify their properties in most cases. In the following example, every variable (i and j) defined in the parallel for loop is private by default.

#pragma omp parallel for
for(int i=0; i<n; i++) {
  for(int j=0; j<n; j++) {
    //do something
  }
}



回答2:


Technically it does not make a difference, because the standard explicitly states the loop variable in the canonical loop form is always implicitly private.

If this variable would otherwise be shared, it is implicitly made private in the loop construct.

[2.6 in OpenMP API 4.5]

I would advise against declaring it shared, it would be very confusing to to anyone trying to read the program. You might argue that you could have the variable being shared outside of the loop and private inside, but I can't think of a case where this would make sense.

I'd hoped the compiler would give you a warning in that case, but at least GCC does not.



来源:https://stackoverflow.com/questions/37845291/openmp-outer-loop-private-or-shared

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!