c++ - 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
都应添加到一个最终结果中。
我怎样才能做到这一点?
解决方案
#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
是在循环中定义的局部变量。
推荐阅读
- html - 的奇怪行为
代替
- node.js - 目标入口点“@vcd/ui-components”缺少依赖项:
- java - android studio java使用蓝牙错误从arduino接收数据
- c++ - 关于 CMake 错误的问题:没有给目标提供源
- node.js - 从 sql 查询结果中删除 [TextRow]
- spring-boot - QueryDsl BooleanExpression - 嵌套字段为 NULL
- node.js - Puppeteer - 铬 | 无法打开 X 显示器 | Ubuntu 20.04
- angular - 角度垫选择和垫选项未显示
- javascript - 一次导入目录中的所有文件
- c++ - 空基虚拟方法是否已优化?