OpenMP最小值数组 [英] OpenMP minimum value array

查看:308
本文介绍了OpenMP最小值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有原始代码:

min = INT_MAX;
for (i=0;i<N;i++)
  if (A[i]<min) 
    min = A[i];
for (i=0;i<N;i++)
  A[i]=A[i]-min;

我想得到这个的并行版本,我做到了:

I want to get the parallel version of this and I did this:

min = INT_MAX;
#pragma omp parallel private(i){
minl = INT_MAX;
#pragma omp for
for (i=0;i<N;i++)
  if (A[i]<minl)
    minl=A[i];
#pragma omp critical{
if (minl<min)
  min=minl;
}
#pragma omp for
for (i=0;i<N;i++)
  A[i]=A[i]-min;
}

并行代码正确吗?我想知道是否有必要在#pragma omp关键之前写#pragma omp屏障,以便确保在计算全局最小值之前已计算所有最小值.

Is the parallel code right? I was wondering if it is necessary to write #pragma omp barrier before #pragma omp critical so that I make sure that all the minimums are calculated before calculating the global minimum.

推荐答案

代码正确.不必添加#pragma omp barrier,因为当一个线程进入关键部分时,无需计算所有min_l.循环区域的末尾还有一个隐式屏障.

The code is correct. There is no necessity to add a #pragma omp barrier because there is no need for all min_l to be computed when one thread enters the critical section. There is also an implicit barrier at the end of the loop region.

此外,您不必显式声明循环迭代变量i私有.

Further, you do not necessarily need to explicitly declare the loop iteration variable i private.

您可以通过使用精简代替手动合并minl来改进代码:

You can improve the code by using a reduction instead of your manual merging of minl:

#pragma omp for reduction(min:min)
for (i=0;i<N;i++)
  if (A[i]<min)
    min=A[i];

注意:从OpenMP 3.1开始,用于还原的min运算符可用.

Note: The min operator for reduction is available since OpenMP 3.1.

这篇关于OpenMP最小值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆