c - OpenMP 线程 ID 如何与递归一起使用?

标签 c recursion openmp

这是一个简单的递归程序,每次递归调用都将其分成两部分。正如预期的那样,结果是对 rec 的 2 + 4 + 8 次调用,但线程数始终相同:两个,并且 id 在 0 和 1 之间来回跳动。我希望每次递归调用都保留 id,最后会创建 8 个线程。究竟是怎么回事?代码有问题吗?

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

void rec(int n) {
  if (n == 0)
    return;

  #pragma omp parallel num_threads(2)
  {
    printf("Currently at %d -- total %d\n", omp_get_thread_num(), omp_get_num_threads());
    rec(n - 1);
  }
}

int main() {
  omp_set_nested(1);
  rec(3);
}

最佳答案

您的代码按照 OpenMP 标准的预期运行。在 OpenMP documentation您可以找到有关 omp_get_num_threads 的以下内容:

Summary: The omp_get_num_threads routine returns the number of threads in the current team.

Binding: The binding region for an omp_get_num_threads region is the innermost enclosing parallel region.

Effect: The omp_get_num_threads routine returns the number of threads in the team that is executing the parallel region to which the routine region binds. If called from the sequential part of a program, this routine returns 1.

omp_get_thread_num具有相同的结合区域:

The binding region for an omp_get_thread_num region is the innermost enclosing parallel region.

这意味着 omp_get_num_threadsomp_get_thread_num 仅绑定(bind)到最里面的并行区域,因此使用多少嵌套并行区域并不重要。每个并行区域都由 #pragma omp parallel num_threads(2) 定义,因此 omp_get_num_threads 的返回值为 2(只要您有足够的线程可用)并且omp_get_thread_num 的返回值为 01

关于c - OpenMP 线程 ID 如何与递归一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71504894/

相关文章:

c - 递归难度

javascript - 动态嵌套for循环用递归解决

c++ - PGI 不支持 OpenMP 4.5 运行时函数

c++ - 在无法应用omp atomic/reduction的情况下,使用omp critical我们可以做些什么来提高效率呢?

c - 如何等待30小时?

c - realloc() 结构数组的旧大小无效

使用 make 编译多个 C 文件

function - 本地函数相互调用

c++ - 基准问题 : execution time varies between two values

c - 共享库中的 gdb 断点不起作用