为此,OpenMP 标准提出了该指令的depend
条款。task
在您的特定情况下,我想这可以像这样使用:
#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;
}
如您所见,我引入了一些变量a
,b
并c
使用它们来定义任务之间的依赖关系。我也在调用中相应地修改它们,尽管这不是必需的(我这样做只是为了展示如何处理流程)。
这是我在我的机器上得到的:
~/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