为什么从OpenMP程序中获取不正确的结果?

时间:2018-01-02 22:26:23

标签: c parallel-processing openmp

我正在编写一些简单的示例来了解OpenMP程序的工作原理。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <omp.h>

int main (int argc ,char* argv[]){
    omp_set_num_threads(4);
    int j =0;
    #pragma omp parallel private (j)
    {
    int i;
    for(i=1;i<2;i++){
        printf("from thread %d : i is equel to  %d and j is equal to %d\n ",omp_get_thread_num(),i,j);

    }
    }
}

因此,在此示例中,我每次都应 j=0
很遗憾,结果是 j == 0 3次 j == 32707 一次。

我的例子出了什么问题?

1 个答案:

答案 0 :(得分:1)

如果您希望每个帖子都有 firstprivate(j) 的私有副本,并且初始值为进入并行之前的值,请使用private(j)而不是j区域。