两个不同的 pragma for-s 之间是否有障碍

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

有8个城市。我们对每个城市的不同统计数据进行计算。

我需要知道for循环的末尾是否有障碍,以便在所有其他先前城市的统计数据完成后开始下一组计算。

肯定是这样的,因为每次计算都依赖于前一次。

#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

是的,如果你使用#pragma omp parallel for,你将在循环结束时有一个隐式屏障,等待所有线程完成后再继续执行。

不需要放置明确的pragma omp barrier

根据OpenMP 4.0 Complete Specifications(1.3 第 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.

阿齐兹回答正确但不完整。

#pragma omp for

没有 parallel 仍然很好。

OpenMP 中的任何工作共享结构(包括循环结构 omp for)在末尾都有一个隐式屏障。这可以通过 nowait 子句禁用。

没有必要使用 omp parallel for,这也是不可取的,因为会增加线程管理开销。