c - 没有得到正确的总和 - openmp

标签 c openmp

当我运行此代码时,我得到 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/

相关文章:

c++ - 任务按处理时间排序时,openMp动态调度和LPT调度一样吗?

C stdio 无缓冲多路复用

检查 C 中的溢出

c - C中的逻辑数组

c - 使用 openmp 并行化此 C 代码

c - OpenMP 并行区域线程关联

c - 关于类型,c 中的 `int (*)(int)` 是什么意思?

c - 共享内存的 MPI_Comm_Size 值

c - OpenMP C 程序运行速度比顺序代码慢

使用 OpenMP 计算直方图