OpenMP 提供不一致的数据顺序

OpenMP giving inconsistent order of data

我使用 OpenMP 在 C 中编写了代码,但编译时前四个结果总是顺序不同,运行 时间仅在大约一半的时间显示非 0 的值。我错过了什么吗?这是代码:

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

void test(int *ptr0, int *ptr1, int n)
{
    int sum=0, i;
    int id=omp_get_thread_num();

    for(i=0;i<16;i++){
        sum+=prt0[i]*ptr1[i];
    }

    printf("Sum = %d from thread %d\n",sum,id);
}

int main()
{
    int m=64, n=16, a, b;

    int** array0=calloc(m, sizeof(int*));
    for(a=0;a<m;a++){
        array0[a]=calloc(n, sizeof(int));
    }

    int** array1=calloc(m, sizeof(int*));
    for(b=0;b<m;b++){
        array1[b]=calloc(n, sizeof(int));
    }

    for(i=0;i<16;i++);{
        array0[i][n/2]=i;
        array1[i][n/2]=i;
    }

    #pragma omp parallel for schedule(dynamic)
        for(i=0;i<n;i++){
            test(array0[i],array1[i],n);
        }

    double start_time, run_time;
    start_time=omp_get_wtime();
    run_time=omp_get_wtime()-start_time;
    printf("Total run time = %.5g seconds\n", run_time);

}

结果是(前 4 行有不同的变化):

Sum = 0 from thread 3
Sum = 1 from thread 1
Sum = 4 from thread 2
Sum = 9 from thread 3
Sum = 16 from thread 0
Sum = 25 from thread 1
Sum = 36 from thread 2
Sum = 49 from thread 3
Sum = 64 from thread 0
Sum = 81 from thread 1
Sum = 100 from thread 2
Sum = 121 from thread 3
Sum = 144 from thread 0
Sum = 169 from thread 1
Sum = 196 from thread 2
Sum = 225 from thread 3
Total run time = 3.95e-07 seconds

关于如何使结果与 0、1、4、9 等的总和以及 运行 不是 0 秒的时间一致的任何建议?

为什么通过请求行中的当前开始和结束时间来期望较长的持续时间?你不想测量什么吗?我猜你的真正目标是在循环开始之前获取开始时间,在所有测试完成后获取结束时间。

您无法控制输出的顺序,因为您无法控制线程的工作速度。只需将结果放在一个附加数组中并在主线程中打印内容。