End*_*lPG 6 c++ for-loop 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;
Run Code Online (Sandbox Code Playgroud)
我认为该变量a必须是每个线程的局部变量。这些线程结束其工作后,所有局部变量a都应添加到一个最终结果中。
我怎样才能做到这一点?
有很多机制可以实现您的目标,但最简单的是采用 OpenMP 并行缩减:
float a = 0.0f;
#pragma omp parallel for reduction(+:a)
for(int i = 0; i < x; i++)
a += algorithm();
cout << a;
Run Code Online (Sandbox Code Playgroud)
#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;
Run Code Online (Sandbox Code Playgroud)
相当于:
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;
Run Code Online (Sandbox Code Playgroud)
请注意,您不能创建带有停止条件的 for 循环i<x,其中x是循环内定义的局部变量。