并行区域声明外部函数后 OpenMP 减少
OpenMP reduction after parallel region declared outside function
抱歉,如果有人问过这个问题,我无法轻易找到我的具体问题的答案。
我有正在并行化的代码。我想在函数调用之外声明一个并行区域,但在函数内部我需要做一些缩减操作。
代码的基本形式为:
#pragma omp parallel
{
for(j=0;j<time_limit;j++)
{
//do some parallel loops
do_stuff(arg1, arg2)
}
}
...
...
void do_stuff(int arg1, int arg2)
{
int sum=0;
#pragma omp for reduction(+:sum) //the sum must be shared between all threads
for(int i=0; i<arg1;i++)
{
sum += something;
}
}
当我尝试编译时,reduction 子句抛出错误,因为变量 sum
对于每个线程都是私有的(很明显,因为它是在并行区域内声明的)。
有没有办法在不必在函数内声明并行区域的情况下进行这种缩减(或具有相同最终结果的方法)do_stuff
?
如果你只想减少功能,你可以使用静态存储。来自 OpenMP 4.0.0 specification
的 2.14.1.2
Variables with static storage duration that are declared in called routines in the region are shared.
#include <stdio.h>
void do_stuff(int arg1, int arg2)
{
static int sum = 0;
#pragma omp for reduction(+:sum)
for(int i=0; i<arg1;i++) sum += arg2;
printf("sum %d\n", sum);
}
int main(void) {
const int time_limit = 10;
int x[time_limit]; for(int i=0; i<time_limit; i++) x[i] = i;
#pragma omp parallel
{
for(int j=0;j<time_limit;j++) do_stuff(10,x[j]);
}
}
抱歉,如果有人问过这个问题,我无法轻易找到我的具体问题的答案。
我有正在并行化的代码。我想在函数调用之外声明一个并行区域,但在函数内部我需要做一些缩减操作。
代码的基本形式为:
#pragma omp parallel
{
for(j=0;j<time_limit;j++)
{
//do some parallel loops
do_stuff(arg1, arg2)
}
}
...
...
void do_stuff(int arg1, int arg2)
{
int sum=0;
#pragma omp for reduction(+:sum) //the sum must be shared between all threads
for(int i=0; i<arg1;i++)
{
sum += something;
}
}
当我尝试编译时,reduction 子句抛出错误,因为变量 sum
对于每个线程都是私有的(很明显,因为它是在并行区域内声明的)。
有没有办法在不必在函数内声明并行区域的情况下进行这种缩减(或具有相同最终结果的方法)do_stuff
?
如果你只想减少功能,你可以使用静态存储。来自 OpenMP 4.0.0 specification
的 2.14.1.2Variables with static storage duration that are declared in called routines in the region are shared.
#include <stdio.h>
void do_stuff(int arg1, int arg2)
{
static int sum = 0;
#pragma omp for reduction(+:sum)
for(int i=0; i<arg1;i++) sum += arg2;
printf("sum %d\n", sum);
}
int main(void) {
const int time_limit = 10;
int x[time_limit]; for(int i=0; i<time_limit; i++) x[i] = i;
#pragma omp parallel
{
for(int j=0;j<time_limit;j++) do_stuff(10,x[j]);
}
}