Search code examples
cmultithreadingparallel-processingtaskopenmp

OpenMP tasks and Thread creation


I want to get IDs of different threads in an OpenMP program. Why I get the same thread ID for the below code?

#pragma omp task untied
     id1 = omp_get_thread_num(); printf("TID:%d\n",id1);
     foo_par(A);
#pragma omp task untied
     id2 = omp_get_thread_num(); printf("TID:%d\n",id2);
     foo_par(B);
 ....

Why I get '0' for both id1 and id2?


Solution

  • With your code:

    #pragma omp task untied
         id1 = omp_get_thread_num(); printf("TID:%d\n",id1);
         foo_par(A);
    #pragma omp task untied
         id2 = omp_get_thread_num(); printf("TID:%d\n",id2);
         foo_par(B);
    

    Since, you are not using {} only this instruction omp_get_thread_num(); will became a task.

    Btw, remember that the task pragma is available since OpenMP 3.0, so if your GCC is an older version that 4.4, the task directives will be ignored.

    Try the following:

    #pragma omp parallel region
    {
      #pragma omp single
      {
       #pragma omp task untied
       {
         id1 = omp_get_thread_num(); printf("TID:%d\n",id1);
         foo_par(A);
       }
    
       #pragma omp task untied
       {
         id2 = omp_get_thread_num(); printf("TID:%d\n",id2);
         foo_par(B);
       }
     }
    }
    

    The single construct is needed so that tasks would be created by one thread only. Otherwise, each task would get created N times (N == number of threads).

    Note that, if one thread 'X' is able to finish their work and request for another task in the pool it may start before another thread in the team. In another words, even if you have defined 2 different task (for example), the tasks might be executed by the same thread.