首页 > 解决方案 > for循环openmp中的局部变量

问题描述

我刚刚开始使用 openmp 进行编程,并且正在尝试将for循环与我需要的变量并行化。像这样的东西:

float a = 0;
for (int i = 0; i < x; i++)
{
    int x = algorithm();
    /* Each loop, x have a different value*/
    a = a + x;
}
cout << a;

我认为该变量a必须是每个线程的局部变量。在这些线程结束其工作后,所有局部变量a都应添加到一个最终结果中。

我怎样才能做到这一点?

标签: c++for-loopopenmp

解决方案


#pragma omp parallel for reduction(+:a)在 for 循环之前使用子句

在循环内声明的变量for是本地的,在块外声明的循环计数器变量#pragma omp parallel默认是共享的,除非另有说明(参见shared, private,firstprivate子句)。更新共享变量时应小心,因为可能会出现竞争条件。在这种情况下,reduction(+:a)子句表明a是一个共享变量,在每个循环中都对其执行加法。线程将自动跟踪要添加的总量,并在循环结束时安全地递增 a。

下面的两个代码是等效的:

float a = 0.0f;
int n=1000;
#pragma omp parallel shared(a) //spawn the threads
{
float acc=0;        // local accumulator to each thread
#pragma omp for     // iterations will be shared among the threads
for (int i = 0; i < n; i++){
      float x = algorithm(i); //do something
      acc += x;     //local accumulator increment
  } //for
#omp pragma atomic
a+=acc; //atomic global accumulator increment: done on thread at a time
} //end parallel region, back to a single thread
cout << a;

相当于:

float a = 0.0f;
int n=1000;
#pragma omp parallel for reduction(+:a)
for (int i = 0; i < n; i++){
    int x = algorithm(i);
    a += x;
    } //parallel for
cout << a;

请注意,您不能创建带有停止条件的 for 循环,i<x其中x是在循环中定义的局部变量。


推荐阅读