我有这个老问题,但我在网上找不到任何答案,代码是:
#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;
}
在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
如果我们转到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
有什么想法吗?
答案 0 :(得分: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;
}
答案 1 :(得分:6)
您在编译时几乎肯定忘记使用-fopenmp
flag。
答案 2 :(得分:3)
在程序的连续部分中,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)来指定 线程数。
答案 3 :(得分:2)
正如所指出的,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;
}
与-fopenmp
编译并运行。输出应为:
$ gcc -fopenmp test.c
$ ./a.out
num_threads = 4
当然,4
正是我的电脑默认显示的内容;在您的计算机上,它将打印默认线程数(核心数,或环境变量OMP_NUM_THREADS
的值,如果已设置)。
我测试了这个解决方案,发现它适用于Linux上的gcc 4.8.5,Linux上的icc 18.0.1,macOS上的gcc 6.4.0和macOS上的clang 3.9.1。