当我运行此代码时,我得到 2542199.979500
作为答案。然而,正确的答案是1271099.989750
。有人可以告诉我错误在哪里吗?
这是包含错误的代码:
#include <omp.h>
#define N 1000
main ()
{
int i, nthreads;
int chunk = 10;
float a[N], b[N], c[N], d[N];
double result;
#pragma omp parallel
{
nthreads = omp_get_num_threads();
printf("no of threads %d", nthreads);
#pragma for shared(a,b,c,d,result) private(i) schedule(static,chunk)
for (i=0; i < N; i++){
a[i] = i * 1.5;
b[i] = i + 22.35;
}
#pragma for shared(a,b,c,d,result) private(i) schedule(static,chunk)
for(i=0; i < N; i++){
result = result + (a[i]+b[i]);
}
}
printf("value is %f", result);
}
此外,当线程数为 3 时,我得到
3813299.969250
结果取决于使用的线程数。这可能是 openmp 中的一个错误,还是我做错了什么?
最佳答案
我建议至少进行以下两项更改...
用于声明结果
...
// result should be initialized
double result = 0;
最后的编译指示...
// specify the "reduction"
#pragma omp parallel for reduction(+:result)
如果不指定“减少”,对结果
的求和是无效的,因为结果
将在每个线程中独立修改——导致竞争条件。
参见http://en.wikipedia.org/wiki/OpenMP#Reduction
<小时/>#include <stdio.h>
#include <omp.h>
#define N 1000
int main ()
{
int i, nthreads;
int chunk = 10;
float a[N], b[N], c[N], d[N];
double result=0;
#pragma omp parallel
nthreads = omp_get_num_threads();
printf("no of threads %d\n", nthreads);
#pragma omp parallel for
for (i=0; i < N; i++){
a[i] = i * 1.5;
b[i] = i + 22.35;
}
#pragma omp parallel for reduction(+:result)
for(i=0; i < N; i++){
result = result + (a[i]+b[i]);
}
printf("value is %f", result);
return 0;
}
关于c - 没有得到正确的总和 - openmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901678/