c++ - OpenMP 4 中的任务依赖性

标签 c++ parallel-processing dependencies task openmp

以下代码基于 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:为什么输入输出依赖任务应该依赖于输入依赖任务?

我只想让您注意到,使用此规则,您将在运行结束时获得变量 xy 的确定值(假设您注意同步访问内存)。如果 task3 依赖于 task1 而不是 task2,则此确定性将不成立(inout 依赖等同于 in 依赖)。


问题 3:我需要做什么才能让他们独立?

inout:x依赖转化为in:x依赖,通过atomic同步访问x条款。这样你就可以运行:

  • x == 2y == 2
  • x == 2y == 3

取决于 task2 是否在 task3 之前执行。

关于c++ - OpenMP 4 中的任务依赖性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475174/

相关文章:

c++ - 需要有关 Vigenere Cipher 程序的帮助

shell - 如何防止并行向我的命令添加额外的转义?

MySQL外键依赖解析

multithreading - 在 Azure 中执行多线程的正确方法是什么

android - 程序类型已经存在 : com. google.common.util.concurrent.internal.InternalFutureFailureAccess

android - 尝试将 ADT 插件安装到 Eclipse 时发生依赖冲突

c++ - 与 Python 一起运行 C++ 代码并与之交互

c++ - 系统头文件/usr/include/i386_types.h错误

c++ - 调用任何指定函数的函数

python - numba @jit 比纯 python 慢?