我得到omp_get_num_threads总是在gcc中返回1(在icc中工作)

ios*_*ner 4 gcc openmp icc

我有这个老问题,但在线没有回答对我有用,代码是:

#include "stdio.h"
#include "omp.h"

main ()
{
    omp_set_num_threads(4); //initialise thread count for 4 core cpu                                                                                                                             
    int j;
    printf ("%d\n", omp_get_max_threads());
    printf ("%d\n", omp_get_num_threads());
#pragma omp parallel for
    for (int j=0; j<10; ++j)
        {
            printf ("%d\n", omp_get_num_threads());
            int threadNum;
            threadNum = omp_get_thread_num();
            printf("This is thread %d\n", threadNum);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在G ++ 4.4.5,linux 2.6.32-5-amd64中,它产生:

4
1
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
1
This is thread 0
Run Code Online (Sandbox Code Playgroud)

如果我们转向ICC 12.1.0,它会给我:

4
1
4
This is thread 0
4
This is thread 0
4  
This is thread 0
4
This is thread 1
4
This is thread 1
4
This is thread 1
4
This is thread 2
4 
This is thread 2
4
This is thread 3
4
This is thread 3
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 17

我从未见过omp_get_num_threads()gcc合作过.
我使用自己的例程来计算正在运行的线程数:

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

int omp_thread_count() {
    int n = 0;
    #pragma omp parallel reduction(+:n)
    n += 1;
    return n;
}

int main() {
    printf("%d, %d\n",omp_thread_count(),omp_get_num_threads());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Leo*_*Leo 10

正如所指出的,omp_get_num_threads()在顺序代码段中总是返回 1。这是我想出的解决该限制的最简单方法:

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

int main(int argc, char **argv)
{
  #pragma omp parallel
  {
    #pragma omp single
    printf("num_threads = %d\n", omp_get_num_threads());
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译-fopenmp并运行。输出应该是:

$ gcc -fopenmp test.c
$ ./a.out
num_threads = 4
Run Code Online (Sandbox Code Playgroud)

当然,4这只是我的电脑默认显示的;在您的计算机上,它将打印默认线程数(内核数或环境变量的值(OMP_NUM_THREADS如果已设置))。

我测试了这个解决方案,发现它适用于 Linux 上的 gcc 4.8.5、Linux 上的 icc 18.0.1、macOS 上的 gcc 6.4.0 和 macOS 上的 clang 3.9.1。


Oli*_*rth 7

在编译时,你几乎肯定忘了使用-fopenmp旗帜.

  • 我没有忘记那面旗帜,但对我来说它仍然是1. (3认同)

小智 5

在程序的连续部分 omp_get_num_threads 返回 1。(https://gcc.gnu.org/onlinedocs/libgomp/omp_005fget_005fnum_005fthreads.html

只有在并行部分 omp_get_num_threads 才会返回 1 以外的值。

我试过 gcc-4.9.1。omp_get_num_threads() 仍然返回 1。

icc 和 gcc 对线程数的识别不同。

使用 icc-10,我可以使用 maxNumCompThreads(2) 来指定线程数。