Search code examples
copenmpbarrier

Do two different pragma for-s have a barrier between them


There are 8 cities. we do calculations for different stats of each city.

I need to know if there is a barrier at the end of a for loop, so that the next group of calculation starts after all other previous cities' stats are done.

It must be like this, because each calculation depends from the previous one.

#pragma omp for
for (int i = 0; i < count; ++i)
{
    // calculate stats about population
}

// is there a barrier in here?
// Or do I need an explicit barrier
// #pragma omp barrier

#pragma omp for
for (int i = 0; i < count; ++i)
{
    // calculate stats about cars 
}

// is there a barrier in here?

#pragma omp for
for (int i = 0; i < count; ++i)
{
    // calculate stats about weather 
}

// ...same idea

Solution

  • Yes, if you use #pragma omp parallel for, you will have an implicit barrier at the end of the loop waiting for all threads to finish before continuing the execution.

    You don't need to place an explicit pragma omp barrier.

    According to OpenMP 4.0 Complete Specifications (1.3 line 10):

    The task region of the task being executed by the encountering thread is suspended, and each member of the new team executes its implicit task. There is an implicit barrier at the end of the parallel construct.