繁体   English   中英

使用openMP的并行程序

[英]Parallel program using openMP

我正在尝试使用OpenMP使用多线程在c ++中从0到1计算4 /(1 + x ^ 2)的积分。 我拿了一个串行程序(正确)并进行了更改。 我的想法是:假设X是线程数。 将函数下方的区域划分为X个部分,首先从0到1 / X,从1 / X到2 / X ...每个线程将计算出它的面积,我将所有面积相加。

这是我的实现方式:

`//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;
    }
} '

说明:第i个线程将计算i / n到(i + 1)/ n之间的面积,并将其添加到总和中。

问题在于,不仅输出错误,而且每次运行程序时,我都会得到不同的输出。

任何帮助都将受到欢迎,谢谢

您使这个问题变得比原本要困难得多。 OpenMP的目标之一是不必更改您的序列号。 通常只需要添加一些编译指示即可。 因此,您应该首先编写串行方法。

#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));
}

输出: 3.141593

注意,在函数pi ,串行代码和并行版本之间的唯一区别是语句

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

您通常也不必担心设置线程数。

暂无
暂无

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

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