工作结束后,是否可以使线程加入“ parallel for”区域?

sun*_*cho 6 c c++ multithreading openmp

我有两项工作需要首先同时运行:

1)for可以并行化的循环

2)可以用一个线程完成的功能

现在,让我描述一下我想做什么。

如果存在8个可用线程,

job(1)和job(2)必须首先分别使用7个线程和1个线程同时运行。

在job(2)完成之后,应该将job(2)使用的线程分配给job(1),它是并行的for循环。

我正在使用omp_get_thread_num来计算每个区域中活动的线程数。我希望完成job(1)时线程数增加1 job(2)

下面介绍了可能是错误或确定的解决方案:

  omp_set_nested(1);
  #pragma omp parallel
  {
    #pragma omp sections
    {
      #pragma omp section // job(2)
      { // 'printf' is not real job. It is just used for simplicity.
        printf("i'm single: %d\n", omp_get_thread_num());
      }
      #pragma omp section // job(1)
      {
        #pragma omp parallel for schedule(dynamic, 32)
        for (int i = 0 ; i < 10000000; ++i) {
          // 'printf' is not real job. It is just used for simplicity.
          printf("%d\n", omp_get_thread_num());
        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

如何完成我想完成的工作?

小智 4

像这样的事情怎么办?

#pragma omp parallel
{
     // note the nowait here so that other threads jump directly to the for loop
    #pragma omp single nowait
    {
       job2();
    }

    #pragma omp for schedule(dynamic, 32)
    for (int i = 0 ; i < 10000000; ++i) {
        job1();
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有对此进行测试,但由于 nowait,单个线程将仅由一个线程执行,而所有其他线程将直接跳转到 for 循环。我还认为它比章节更容易阅读。