0

What I am looking for is what is the best way to gather all the data from the parallel for loops into one variable. OpenMP seems to have a different routine then I am used to seeing as I started learning OpenMPI first which has scatter and gather routines.

Calculating PI (embarrassingly parallel routine)

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_STEPS 100
#define CHUNKSIZE 20

int main(int argc, char *argv[])
{
    double step, x, pi, sum=0.0;
    int i, chunk;

    chunk = CHUNKSIZE;
    step = 1.0/(double)NUM_STEPS;

    #pragma omp parallel shared(chunk) private(i,x,sum,step)
    {

        #pragma omp for schedule(dynamic,chunk)
            for(i = 0; i < NUM_STEPS; i++)
            {
                x = (i+0.5)*step;
                sum = sum + 4.0/(1.0+x*x);
                printf("Thread %d: i = %i sum = %f \n",tid,i,sum);
            }
        pi = step * sum;
    }

EDIT: It seems that I could use an array sum[*NUM_STEPS / CHUNKSIZE*] and sum the array into one value, or would it be better to use some sort of blocking routine to sum the product of each iteration

4

2 回答 2

2

将此子句添加到您的#pragma omp parallel ...语句中:

reduction(+ : pi) 

然后就pi += step * sum;在平行区域的末端做。(注意加号!)OpenMP 然后会自动为您总结部分总和。

于 2013-05-24T20:44:21.123 回答
1

让我们看看,我不太确定会发生什么,因为我在完成的应用程序上没有确定性行为,但我有一些看起来像 π 的东西。我删除了#pragma omp parallel shared(chunk)并将其更改#pragma omp for schedule(dynamic,chunk)#pragma omp parallel for schedule(dynamic) reduction(+:sum).

#pragma omp parallel for schedule(dynamic) reduction(+:sum)

这需要一些解释,我删除了schedules 块只是为了让它更简单(对我来说)。您感兴趣的部分是reduction(+:sum)使用运算符+和使用变量的正常减少操作sum

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_STEPS 100

int main(int argc, char *argv[])
{
    double step, x, pi, sum=0.0;
    int i;

    step = 1.0/(double)NUM_STEPS;

#pragma omp parallel for schedule(dynamic) reduction(+:sum)
    for(i = 0; i < NUM_STEPS; i++)
    {
        x = (i+0.5)*step;
        sum +=4.0/(1.0+x*x);
        printf("Thread %%d: i = %i sum = %f \n",i,sum);
    }
    pi = step * sum;
    printf("pi=%lf\n", pi);
}
于 2013-05-24T20:52:25.127 回答