【发布时间】:2021-11-23 20:25:00
【问题描述】:
我已经编写了以下代码来计算 pi 的值并且它可以工作:
#include <omp.h>
#include <stdio.h>
static long num_steps = 1000000;
double step;
#define NUM_THREADS 16
int main()
{
int i, nthreads;
double tdata, pi, sum[NUM_THREADS];
omp_set_num_threads(NUM_THREADS);
step = 1.0 / (double)num_steps;
tdata = 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;
for (i = id, sum[id] = 0.0; i < num_steps; i = i + nthrds)
{
x = (i + 0.5) * step;
sum[id] = sum[id] + 4.0 / (1.0 + x * x);
}
}
tdata = omp_get_wtime() - tdata;
for (i = 0, pi = 0.0; i < nthreads; i++)
{
pi = pi + sum[i] * step;
}
printf("pi=%f and it took %f seconds", pi, tdata);
}
然后我了解到我可以使用#pragma omp parallel for,然后我不必手动将计算中断到不同的线程。所以我写了这个:
#include <omp.h>
#include <stdio.h>
static long num_steps = 1000000;
double step;
#define NUM_THREADS 16
int main()
{
int i;
double tdata, pi, x, sum = 0.0;
omp_set_num_threads(NUM_THREADS);
step = 1.0 / (double)num_steps;
tdata = omp_get_wtime();
#pragma omp parallel for
{
for (i = 0; i < num_steps; i++)
{
x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + x * x);
}
}
tdata = omp_get_wtime() - tdata;
pi = sum * step;
printf("pi = %f and compute time = %f seconds", pi, tdata);
}
但是,这不起作用并输出错误的 pi 值。我究竟做错了什么?谢谢。
【问题讨论】:
标签: c multithreading parallel-processing thread-safety openmp