openmp的减少有什么用? [英] What is the usage of reduction in openmp?

查看:88
本文介绍了openmp的减少有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段并行的代码.

int i,n; double area,pi,x;
area=0.0;
#pragma omp parallel for private(x) reduction (+:area)
for(i=0; i<n; i++){
x= (i+0.5)/n;
area+= 4.0/(1.0+x*x);
}
pi = area/n;

据说减法将消除如果我们不使用减法可能发生的竞赛条件.仍然我想知道我们是否需要为区域添加lastprivate,因为它在并行循环之外使用并且在它的外部不可见.减少量是否还涵盖了这一点?

It is said that the reduction will remove the race condition that could happen if we didn't use a reduction. Still I'm wondering do we need to add lastprivate for area since its used outside the parallel loop and will not be visible outside of it. Else does the reduction cover this as well?

推荐答案

您不需要lastprivate.为了帮助您了解如何完成减少操作,我认为查看如何使用atomic完成操作很有用.以下代码

You do not need lastprivate. To help you understand how reductions are done I think it's useful to see how this can be done with atomic. The following code

float sum = 0.0f;
pragma omp parallel for reduction (+:sum)
for(int i=0; i<N; i++) {
    sum += //
}

等同于

float sum = 0.0f;
#pragma omp parallel
{
    float sum_private = 0.0f;
    #pragma omp for nowait
    for(int i=0; i<N; i++) {
        sum_private += //
    }
    #pragma omp atomic
    sum += sum_private;
}

尽管此替代方法具有更多代码,但有助于说明如何使用更复杂的运算符.使用reduction时的一个限制是atomic仅支持一些基本运算符.如果要使用更复杂的运算符(例如,添加SSE/AVX),则可以将atomic替换为critical

Although this alternative has more code it is helpful to show how to use more complicated operators. One limitation when suing reduction is that atomic only supports a few basic operators. If you want to use a more complicated operator (such as a SSE/AVX addition) then you can replace atomic with critical reduction with OpenMP with SSE/AVX

这篇关于openmp的减少有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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