7
votes
    #include<omp.h>
    #include<stdio.h>
    #include<stdlib.h>

    void main(int argc, int *argv[]){


   #pragma omp parallel num_threads(3)
   {

    int tid = omp_get_thread_num();
    printf("Hello world from thread = %d \n",tid);
    if(tid == 0){
        int nthreads = omp_get_num_threads();
        printf("Number of threads = %d\n",nthreads);
    }
   }

  }

I am learning OpenMP and I don't understand why it executes only one thread when I have specified the number of threads 3? The program ouptut:

   Hello world from thread = 0
   Number of threads = 1
3
You may have compiled it in a wrong way. In gcc for example, if you compile and link separately be sure to have -fopenmp for linking and compiling. It should be similar for other compilers as well.andreee
How did you compile this? If it was in Visual Studio, you will have to explicitly enable OpenMP.Jonathan Dursi

3 Answers

3
votes
3
votes

You need to compile your program with -fopenmp.

g++ a.cc -fopenmp
0
votes

omp_get_num_threads() returns the total number of threads being used

omp_get_thread_num() returns the current thread ID

You should use the former one