gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:29:45 26 4
gpt4 key购买 nike

我正在 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 usedto form a new team if a parallel construct without a num_threadsclause were encountered after execution returns from this routine.

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com