【发布时间】:2019-02-08 12:13:46
【问题描述】:
我刚开始学习 openmp 编程,但被困在一段代码中,该代码试图并行化程序以计算 pi。我无法理解这一行在程序中的作用以及后续评论的含义。
if (id == 0) nthreads = nthrds; //Only one thread should copy the number of threads to the global value to make sure multiple threads writing to the same address don’t conflict.
整个代码是:
#include<omp.h>
#include<stdio.h>
#define NUM_THREADS 2
static long num_steps = 100000;
double step;
int main ()
{
int i, nthreads;
double pi, sum[NUM_THREADS];
step = 1.0/(double) num_steps;
omp_set_num_threads(NUM_THREADS);
double time1 = omp_get_wtime();
#pragma omp parallel
{
int i, id,nthrds;
double x;
id = omp_get_thread_num();
nthrds = omp_get_num_threads();
if (id == 0) nthreads = nthrds; //Only one thread should copy
the number of threads to the global value to make sure multiple
threads writing to the same address don’t conflict.
for (i=id, sum[id]=0.0;i< num_steps; i=i+nthrds){
x = (i+0.5)*step;
sum[id] += 4.0/(1.0+x*x);
}
}
double time2 = omp_get_wtime();
for(i=0, pi=0.0;i<nthreads;i++)pi += sum[i] * step;
printf("%lf\n",pi);
printf("%lf\n",(time2-time1));
}
我尝试在没有 if 语句的情况下运行,但它给出了 pi 0 的值,但在其他情况下运行正确(给出 3.141593)。当我尝试分配 nthreads 等于全局外部的线程总数(即 2)时,它仍然给出了正确的 pi 值。谁能解释一下输出有什么不同?
谢谢!!
【问题讨论】:
标签: openmp