OpenMP tasks and theme creation

I want to get IDs of different threads in an OpenMP program (Linux C code). Why am I getting the same thread ID for the code below?

#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 am I getting '0' for id1 and id2?

+3


source to share


2 answers


With 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 become a task.

Btw, remember it's task pragma

available since OpenMP 3.0

, so if your GCC is an older version since 4.4, 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);
   }
 }
}

      

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

Note that if one thread "X" can terminate and request another task in the pool, it can start before another thread in the command. In other words, even if you have defined two different tasks (for example), tasks can be performed by the same thread.

+2


source


Try

#pragma omp task untied
if (omp_get_thread_num() == 1)
  foo_par(A);
else
  foo_par(B);

      



GDB can be used to debug a program with multiple threads . Use this to step through your code to find out the values omp_get_thread_num()

for each thread; though, this will be obvious when debugging.

+1


source