OpenMP最小值数组

编程入门 行业动态 更新时间:2024-10-16 18:39:58
本文介绍了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最小值数组

本文发布于:2023-11-07 10:41:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   最小值   OpenMP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!