c++ - omp_get_max_threads() 在并行区域返回 1,但它应该是 8

标签 c++ multithreading openmp

我正在 Linux 上编译一个复杂的 C++ 项目,它使用 OpenMP,用 CMake 和 GCC 7 编译。 我在这个特定项目中遇到的奇怪问题是 OpenMP 显然可以正常工作,但它认为只支持 1 个线程,而实际上应该是 8 个。但是,如果我手动指定线程数,它确实会加速代码。

logOut << "In parallel? " << omp_in_parallel() << std::endl;
logOut << "Num threads = " << omp_get_num_threads() << std::endl;
logOut << "Max threads = " << omp_get_max_threads() << std::endl;

logOut << "Entering my parallel region: " << std::endl;

//without num_threads(5), only 1 thread is created
#pragma omp parallel num_threads(5) 
  {          
      #pragma omp single nowait
      {
          logOut << "In parallel? " << omp_in_parallel() << std::endl;
          logOut << "Num threads = " << omp_get_num_threads() << std::endl;
          logOut << "Max threads = " << omp_get_max_threads() << std::endl;
      }
  }

输出:

[openmp_test] In parallel? 0
[openmp_test] Num threads = 1
[openmp_test] Max threads = 1
[openmp_test] Entering my parallel region: 
[openmp_test] In parallel? 1
[openmp_test] Num threads = 5
[openmp_test] Max threads = 1

更奇怪的是,一个简单的测试 OpenMP 程序直接将并行区域内外的最大线程数正确报告为 8。 我一直在梳理所有 CMake 文件,试图找到该项目行为不同的原因的任何指标,但到目前为止我什么也没发现。在我的任何项目文件中都没有提到 omp_set_num_threads,我可以确认 OMP_NUM_THREADS 没有声明。此外,当我在 Windows 上使用 MSVC 编译同一个项目时,这个问题从未发生过。

知道问题出在哪里吗?

(编辑:我扩展了代码示例以表明它不是嵌套的并行 block )

中央处理器:Intel(R) Core(TM) i7-6700K

操作系统:Manjaro Linux 17.0.2

编译器:GCC 7.1.1 20170630

_OPENMP = 201511(我猜这意味着 OpenMP 4.5)

最佳答案

您在并行区域内看到的值似乎是正确的(假设 OMP_NESTED 不正确)。 omp_get_max_threads() 返回如果您要从当前线程并行获取的最大线程数。由于您已经在一个并行区域内(并且我们假设禁用了嵌套并行性),这将是一个。

3.2.3 omp_get_max_threads

Summary
The omp_get_max_threads routine returns an upper bound on the number of threads that could be used to form a new team if a parallel construct without a num_threads clause were encountered after execution returns from this routine.

但这并不能解释为什么您会在平行区域之外看到值 1。 (但它确实回答了标题中的问题,答案是“一个是正确答案”)。

关于c++ - omp_get_max_threads() 在并行区域返回 1,但它应该是 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45472117/

相关文章:

c# - 调用函数的最佳方式是什么?

c - OpenMP 生产者-消费者意外结果

c++ - Windows 上最快的小型数据存储

c++ - 网络摄像头 "still pin"捕获

c++ - 运算符 [] 的重载

c++ - 链式 static_cast 如何定义明确?

java - 线程互斥段

java - 多线程——奇偶序列

c++ - htop 和 OpenMP 线程

c++ - 并行迭代器