生成给定依赖图的 OpenMP 代码

Produce OpenMP code given dependency graph

我有一个问题,关于当您有一个特定的依赖图时如何生成 OpenMP 伪代码。 所以假设我们有这个特定的图表:

解决方案可能是这样的:

    #pragma omp parallel
    {
        #pragma omp single
        {
            A();
            #pragma omp task B();
            #pragma omp task C();
            D();
            #pragma omp taskwait
            #pragma omp task E();
            F();
        }
    }

现在的问题是,虽然上面的代码确实成功实现了重要的并行性,但任务 E 必须等待任务 D 完成,任务 F 必须等待任务 B 完成,根据图表,这不是必需的。

所以我的问题是,有人可以为我提供 OpenMP 伪代码,其中 E 不会等待 D 并且 F 不会等待 B 以获得给定的依赖关系图吗?

为此,OpenMP 标准为 task 指令提出了 depend 子句。

在你的具体情况下,我想这可以这样使用:

#include <stdio.h>

int a, b, c;

void A() {
    a = b = c = 1;
    printf( "[%d]In A: a=%d b=%d c=%d\n", omp_get_thread_num(), a, b, c );
}

void B() {
    a++;
    sleep( 3 );
    printf( "[%d]In B: a=%d\n", omp_get_thread_num(), a );
}

void C() {
    b++;
    sleep( 2 );
    printf( "[%d]In C: b=%d\n", omp_get_thread_num(), b );
}

void D() {
    c++;
    sleep( 1 );
    printf( "[%d]In D: c=%d\n", omp_get_thread_num(), c );
}

void E() {
    a++;
    sleep( 3 );
    printf( "[%d]In E: a=%d, b=%d\n", omp_get_thread_num(), a, b );
}

void F() {
    c++;
    sleep( 1 );
    printf( "[%d]In F: b=%d c=%d\n", omp_get_thread_num(), b, c );
}

int main() {

    #pragma omp parallel num_threads( 8 )
    {
        #pragma omp single
        {
           #pragma omp task depend( out: a, b, c )
           A();
           #pragma omp task depend( inout: a )
           B();
           #pragma omp task depend( inout: b )
           C();
           #pragma omp task depend( inout: c )
           D();
           #pragma omp task depend( inout: a ) depend( in: b )
           E();
           #pragma omp task depend( inout: c ) depend( in: b )
           F();
        }
    }
    printf( "Finally a=%d b=%d c=%d\n", a, b, c );

    return 0;
}

如您所见,我引入了一些变量 abc,用于定义任务之间的依赖关系。我也在调用中相应地修改了它们,尽管这不是必需的(我这样做只是为了展示流程的处理方式)。

这是我在我的机器上得到的:

~/tmp$ gcc -fopenmp depend.c
~/tmp$ ./a.out 
[6]In A: a=1 b=1 c=1
[7]In D: c=2
[2]In C: b=2
[6]In B: a=2
[2]In F: b=2 c=3
[6]In E: a=3, b=2
Finally a=3 b=2 c=3