如何使用 OpenMP 在一段时间内并行化代码 [英] How to parallelise a code inside a while using OpenMP
问题描述
我正在尝试并行化 heat_plate
算法,但我被困在我的 while 中的这段代码中:
I am trying to parallelise the heat_plate
algorithm but I am stuck at this bit of code inside my while:
while(1)
{
.....
.....
#pragma omp parallel shared(diff, u, w) private(i, j, my_diff)
{
my_diff = 0.0;
#pragma omp for
for (i = 1; i < M - 1; i++)
{
for (j = 1; j < N - 1; j++)
{
if ( my_diff < fabs (w[i][j] - u[i][j]))
{
my_diff = fabs (w[i][j] - u[i][j]);
}
}
}
#pragma omp critical
{
if (diff < my_diff)
{
diff = my_diff;
}
}
}
....
....
}
我不仅不能让它并行工作,而且实际上需要更长的时间才能完成
Not only I can't get it to work in parallel it actually takes longer to finish
程序并行运行.
预先感谢您的帮助.
推荐答案
在 OpenMP 中这个数据依赖:
In OpenMP this data dependency:
for (i = 1; i < M - 1; i++)
for (j = 1; j < N - 1; j++)
if ( my_diff < fabs (w[i][j] - u[i][j]))
my_diff = fabs (w[i][j] - u[i][j]);
通常使用 OpenMP 缩减功能,在您的情况下,这将避免 critical
区域(在并行之后),从而提高并行化的整体性能.因此,如果您应用该功能,您的代码将如下所示:
is typically solved using OpenMP reduction feature, which in your case will avoid the critical
region (after the parallel for) and, consequently, improve the overall performance of the parallelization. So if you apply that feature your code would look like the following:
#pragma omp parallel shared(u, w) private(i, j)
{
#pragma omp for reduction(max:diff)
for (i = 1; i < M - 1; i++)
for (j = 1; j < N - 1; j++)
if ( diff < fabs (w[i][j] - u[i][j]))
diff = fabs (w[i][j] - u[i][j]);
}
反过来,您可以将两个 pragma 合并为一个:
In turn you can merge both pragmas into one:
#pragma omp parallel for reduction(max:diff) shared(u, w) private(i, j)
for (i = 1; i < M - 1; i++)
for (j = 1; j < N - 1; j++)
if ( diff < fabs (w[i][j] - u[i][j]))
diff = fabs (w[i][j] - u[i][j]);
这篇关于如何使用 OpenMP 在一段时间内并行化代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!