简体   繁体   English

使用openMP的并行程序

[英]Parallel program using openMP

I am trying to calculate the integral of 4/(1+x^2) from 0 to 1 in c++ with multi-threading using openMP. 我正在尝试使用OpenMP使用多线程在c ++中从0到1计算4 /(1 + x ^ 2)的积分。 I took a serial program (which is correct) and changed it. 我拿了一个串行程序(正确)并进行了更改。 My idea is: Assume that X is the number of threads. 我的想法是:假设X是线程数。 Divide the area beneath the function into X parts, first from 0 to 1/X, 1/X to 2/X... Each thread will calculate it's area, and I will sum it all up. 将函数下方的区域划分为X个部分,首先从0到1 / X,从1 / X到2 / X ...每个线程将计算出它的面积,我将所有面积相加。

This is how I implemented it: 这是我的实现方式:

`//N.o. of threads to do the task
cout<<"Enter num of threads"<<endl;
int num_threads;
cin>>num_threads;

int i; double x,pi,sum=0.0;
step=1.0/(double)num_steps;
int steps_for_thread=num_steps/num_threads;
cout<<"Steps for thread : "<<steps_for_thread<<endl;

//Split to threads
omp_set_num_threads(num_threads);
#pragma omp parallel
{
    int thread_id = omp_get_thread_num();
    thread_id++;

    if (thread_id == 1) 
    {
        double sum1=0.0;
        double x1;
        for(i=0;i<num_steps/num_threads;i++)
        {
            x1=(i+0.5)*step;
            sum1 = sum1+4.0/(1.0+x1*x1);
        }
        sum+=sum1;
    }
    else 
    {
        double sum2=0.0;
        double x2;
        for(i=num_steps/thread_id;i<num_steps/(num_threads-thread_id+1);i++)
        {
            x2=(i+0.5)*step;
            sum2 = sum2+4.0/(1.0+x2*x2);
        }
        sum+=sum2;
    }
} '

Explanation: The i'th thread will calculate the area between i/n to (i+1)/n and add it to the sum. 说明:第i个线程将计算i / n到(i + 1)/ n之间的面积,并将其添加到总和中。

The problem is that not only that the output is wrong, but also each time I run the program I get different output. 问题在于,不仅输出错误,而且每次运行程序时,我都会得到不同的输出。

Any help will be welcomed Thanks 任何帮助都将受到欢迎,谢谢

You're making this problem much harder than it needs to be. 您使这个问题变得比原本要困难得多。 One of OpenMP's goals is to not have to change your serial code. OpenMP的目标之一是不必更改您的序列号。 You usually only need to add some pragma statements. 通常只需要添加一些编译指示即可。 So you should write the serial method first. 因此,您应该首先编写串行方法。

#include <stdio.h>    
double pi(int n) {
        int i;
        double dx, sum, x;
        dx = 1.0/n;
        #pragma omp parallel for reduction(+:sum) private(x)
        for(i=0; i<n; i++) {
                x = i*dx;
                sum += 1.0/(1+x*x);
        }
        sum *= 4.0/n;
        return sum;
}
int main(void) {
        printf("%f\n",pi(100000000));
}

Output: 3.141593 输出: 3.141593

Notice that in the function pi the only difference between the serial code and the parallel version is the statement 注意,在函数pi ,串行代码和并行版本之间的唯一区别是语句

#pragma omp parallel for reduction(+:sum) private(x)

You should also not normally worry about setting the number of threads. 您通常也不必担心设置线程数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM