如何使线程按顺序运行? (OpenMP)

时间:2020-03-29 11:15:11

标签: c linux openmp

已经了解并行编程的工作原理, 但是我有办法打印出线程的顺序吗?

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

int main(int argc, char* argv[])
{
    #pragma omp parallel 
    {
        printf("Hello World... from thread = %d\n",
            omp_get_thread_num());
    }

}

我的输出:


Hello World... from thread = 2
Hello World... from thread = 3
Hello World... from thread = 0
Hello World... from thread = 1

目标输出:


Hello World... from thread = 0
Hello World... from thread = 1
Hello World... from thread = 2
Hello World... from thread = 3

1 个答案:

答案 0 :(得分:1)

如注释中所建议,您可以使用ordered关键字来按顺序获取输出。实际上,您希望有很多独立的计算,然后只按顺序打印(或复制或以其他方式)结果。

这不是专家,但是这是我的方法(在gcc和msvc上有效):

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

int blah(int argc, char* argv[]) {
    // this may or may not be necessary..
    omp_set_num_threads(omp_get_max_threads());

    int i;
#pragma omp parallel
#pragma omp for ordered schedule(static, 1)
    for(i = 0; i < omp_get_num_threads(); i++)
    {
        // This is where the heavy computations go
#pragma omp ordered
        {
            // synchronized and in order; keep this short
            printf("Hello World... from thread = %d\n", omp_get_thread_num());
        }
    }

    return 0;
}

不明白您的问题为何被否决。按顺序排列结果是一个有效的用例,恕我直言。