Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got omp_get_num_threads always return 1 in gcc (works in icc)

Tags:

gcc

icc

openmp

I have this old question but no answer works for me from online, the code is:

#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;
}

In G++ 4.4.5, linux 2.6.32-5-amd64, it produces:

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

If we shift to ICC 12.1.0, it gives me:

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

Any ideas?

like image 690
ios learner Avatar asked Jun 17 '12 11:06

ios learner


1 Answers

I've never seen omp_get_num_threads() work with gcc.
I use my own routine to compute the number of running threads :

#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;
}
like image 53
Steven Brandt Avatar answered Oct 06 '22 01:10

Steven Brandt