OpenMP中单个指令和section指令的区别

Difference between single and sections directive in OpenMP

本文关键字:指令 区别 section 单个 OpenMP      更新时间:2023-10-16

我的理解是我可以使用single指令做与使用sections相同的工作,只需添加nowait标志

下面的代码对我来说和section指令没有什么不同:

    void main(){
    #pragma omp parallel
        {
            int tid = omp_get_thread_num();
    #pragma omp single nowait
            {
                printf("Thread %d in #1 single construct.n", tid);
            }
    #pragma omp single nowait
            {
                printf("Thread %d in #2 single construct.n", tid);
            }
    #pragma omp single nowait
            {
                printf("Thread %d in #3 single construct.n", tid);
            }
        }
    }

谁能给我一些例子使用sectionssingle指令在不同的场景?

首先,singlesections指令在阅读代码时具有明显不同的语义目的,使用一个指令来模仿另一个指令可能会产生很大的误导。

关于技术细节,single是唯一支持copyprivate子句的工作共享指令,它:

…提供使用私有变量的机制将一个隐式任务的数据环境中的值广播给的其他隐式任务的数据环境并行区域。

另一方面,sections工作共享结构支持lastprivatereduction子句,而single不支持。

最后,请注意您的代码片段:

#pragma omp single nowait
        {
            printf("Thread %d in #1 single construct.n", tid);
        }
#pragma omp single nowait
        {
            printf("Thread %d in #2 single construct.n", tid);
        }
#pragma omp single nowait
        {
            printf("Thread %d in #3 single construct.n", tid);
        } // No barrier here

不模仿sections,而是模仿sections nowait。要模拟sections,必须记住让最后一个single构造保持其隐式屏障。

在某些情况下,single nowait结构可能看起来与sections结构的行为方式相同。然而,OpenMP规范只要求只有一个线程执行single构造。它不要求空闲线程承担其他后续构造。您不能简单地依赖于所有OpenMP实现的这种行为。大多数会做你所期望的,但没有保证。

另一件值得一提的事情是,大多数实现使用票务系统将single区域分配给线程。sections通常的代码转换是通过将sections构造转换为for循环并为section构造使用switch语句来映射到for工作共享构造。因此,对于执行有更多的保证。

欢呼,迈克尔。