如何获得在整个程序执行期间可能创建的最大 OpenMP 线程数?

How can I get the maximum number of OpenMP threads that may be created during the whole execution of the program?

我想创建一个全局对象数组(OpenMP 产生的每个可能线程一个对象)并在整个程序中重复使用它。每个线程将使用 omp_get_thread_num 读取其编号,并使用它索引到数组中。

如何获得在整个程序执行期间可能创建的最大 OpenMP 线程数?

omp_get_max_threads 的文档说此函数被指定为 return 一个特定于调用它的特定并行区域的值

omp_get_max_threads – Maximum number of threads of parallel region

Description: Return the maximum number of threads used for the current parallel region that does not use the clause num_threads.

MSDN documentation 的措辞意味着 return 在平行区域之外 omp_get_max_threads 编辑的值与在任何其他区域中 return 编辑的值相同点.

omp_get_max_threads

Returns an integer that is equal to or greater than the number of threads that would be available if a parallel region without num_threads were defined at that point in the code.

哪一个是正确的?

没有最大数量。

从技术上讲,OpenMP 定义了一个名为 nthreads-var 内部控制变量 (请参阅 OpenMP 4.5 2.3.3),它是默认线程数。你用 omp_get_max_threads 读取它,你用 omp_set_num_threads 设置它(一个不幸的命名错误),你用一个明确的 num_threads 子句覆盖它。

因此您必须编写代码,使其能够处理意外数量的线程,例如通过将数组预定义到 omp_get_num_threads() 并在更多线程到达时延迟调整它的大小。或者进行合理的猜测并检查每次访问的索引范围。