以下代码基于 OpenMP 4.0 规范工作:
The out and inout dependence-types. The generated task will be a dependent task of all previously generated sibling tasks that reference at least one of the list items in an in, out, or inout dependence-type list.
这意味着 task3 依赖于 task2。正确的?但它没有意义!为什么输入输出依赖任务应该依赖于输入依赖任务?
我需要做什么才能让他们独立? p.s:代码在 Linux 上使用 g++ 4.9 测试。
#include <stdio.h>
#include <omp.h>
#include <unistd.h>
int main() {
int x,y;
#pragma omp parallel num_threads(10)
{
#pragma omp single nowait
{
#pragma omp task depend (out:x) //task1
{
x=1;
}
#pragma omp task depend(in:x) depend(out:y) //task2
{
sleep(2); //Does task3 wait for us? Yes!
y=x+1;
}
#pragma omp task depend (inout:x) //task3
{
x++;
printf("task3(x): %d\n" , x);
}
#pragma omp task depend (in:x,y) //task4
{
printf("task4 (x+y): %d\n" , x+y);
}
}
}
return 0;
}
最佳答案
问题 1:这意味着 task3 依赖于 task2。对吧?
根据OpenMP 4.0 depend
子句的标准(强调我的):
Task dependences are derived from the dependence-type of a
depend
clause and its list items, where dependence-type is one of the following:The in dependence-type. The generated task will be a dependent task of all previously generated sibling tasks that reference at least one of the list items in an out or inout dependence-type list.
The out and inout dependence-types. The generated task will be a dependent task of all previously generated sibling tasks that reference at least one of the list items in an in, out, or inout dependence-type list.
从这个描述可以看出:
- 子句
depend(in:x)
将生成一个任务,该任务依赖于所有先前使用depend(out:x)
或depend(inout :x)
- 子句
depend(out:x)
或子句depend(inoout:x)
将生成一个依赖于所有先前生成的提及x 的任务的任务
在depend
子句中
将此应用到您的特定案例会给出这种依赖关系链:
task1 (out:x) -> task2 (in:x,out:y) -> task4 (in:x,y)
| ^
| |
> task3 (inout:x)
因此task3依赖于task2的完成。
问题 2:为什么输入输出依赖任务应该依赖于输入依赖任务?
我只想让您注意到,使用此规则,您将在运行结束时获得变量 x
和 y
的确定值(假设您注意同步访问内存)。如果 task3 依赖于 task1 而不是 task2,则此确定性将不成立(inout
依赖等同于 in
依赖)。
问题 3:我需要做什么才能让他们独立?
将inout:x
依赖转化为in:x
依赖,通过atomic
同步访问x
条款。这样你就可以运行:
x == 2
和y == 2
x == 2
和y == 3
取决于 task2 是否在 task3 之前执行。
关于c++ - OpenMP 4 中的任务依赖性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475174/