Ke Du
Ke Du

Reputation: 1

In OpenMP, does explicit barrier synchronize implicit tasks in any ways?

In OpenMP specification 6.0, the barrier construct "specifies an explicit barrier at the point at which the construct appears", and "all threads of the team that executes that binding region must enter the barrier region and complete execution of all explicit tasks", while the parallel region generates implicit tasks for each thread, and expclit tasks are defined as "a task that is not an implicit task", so it seems that a barrier inside a parallel region does not synchronize threads in the implicit tasks at all. However an execution of the following code snippet suggests otherwise:

#include <omp.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    #pragma omp parallel num_threads(2)
    {
        int i =  omp_get_thread_num();
        if (i==0) {
            sleep(1);
        }
        #pragma omp barrier
        printf(" i=%d\n", i);
    }
    return 0;
}

Here only thread number 0 executes the sleep() call, but both threads print after 1 second on my machine. So, does the barrier actually block thread number 1 through some mechanism in OpenMP, or is it just that my compiler happens to implement the barrier construct as something stronger than the specification requires? And if it is the latter case, is there a proper way to put a barrier for implicit tasks, since it sounds like bad practice to rely on this compiler-specific behavior?

Upvotes: 0

Views: 26

Answers (1)

Joachim
Joachim

Reputation: 876

You cited already from the relevant sentence, but you need to read the whole sentence:

Unless the binding region is canceled, all threads of the team that executes that binding region must enter the barrier region and complete execution of all explicit tasks bound to that binding region before any of the threads continue execution beyond the barrier.

The last clause of the sentence provides the synchronization for implicit tasks. All threads and therefore all implicit tasks in the team must enter the barrier before anyone can leave the barrier. "Complete execution" would not make sense for implicit tasks, because the implicit tasks will continue execution after the barrier.

Upvotes: 1

Related Questions