我有 5 个函数 A、B、C、D、E。
要执行 D,我需要执行 B、C,
要执行 E 我需要执行 A、D。
我试过这个
int main()
{
#pragma omp parallel num_threads(5)
{
long t1 = clock();
int a = 0, b = 0, c = 0, d = 0, e = 0;
int th = omp_get_thread_num();
if (th == 0) {
a += A();
printf("A is finished after %d\n", clock() - t1);
}
if (th == 1) {
b += B();
printf("B is finished after %d\n", clock() - t1);
}
if (th == 2) {
c += C();
printf("C is finished after %d\n", clock() - t1);
}
if (th == 3 && (b == 1 && c == 1)) {
d += D();
printf("D is finished after %d\n", clock() - t1);
}
if (th == 4 && (a == 1 && d == 1)) {
e += E();
printf("E is finished after %d\n", clock() - t1);
}
}
return 0;
}
但是D、E还没有执行到目前为止,所有这些函数都返回 1 用于调试目的
最佳答案
一个合适的 OpenMP 解决方案是使用具有数据依赖性的任务:
#pragma omp parallel num_threads(3)
#pragma omp single
{
double t1 = omp_wtime();
int a = 0, b = 0, c = 0, d = 0, e = 0;
#pragma omp task shared(a) depend(out: a)
{
a += A();
printf("A is finished after %f\n", omp_wtime() - t1);
}
#pragma omp task shared(b) depend(out: b)
{
b += B();
printf("B is finished after %f\n", omp_wtime() - t1);
}
#pragma omp task shared(c) depend(out: c)
{
c += C();
printf("C is finished after %f\n", omp_wtime() - t1);
}
#pragma omp task shared(b,c,d) depend(in: b,c) depend(out: d)
{
d += D();
printf("D is finished after %f\n", omp_wtime() - t1);
}
#pragma omp task shared(a,d,e) depend(in: a,d)
{
e += E();
printf("E is finished after %f\n", omp_wtime() - t1);
}
}
在这里,任务A
为 a
的值标记为生产者与 depend(out: a)
和任务D
被标记为 d
的生产者与 depend(out: d)
.任务 E
被标记为这两个值的消费者 depend(in: a,d)
.在输出(生产者)和输入(消费者)依赖之后,OpenMP 运行时构建一个执行 DAG(有向无环图),告诉它所有任务的正确执行顺序。您也不需要五个线程 - 三个就足够了。在
single
中包含任务代码构造是非常惯用的 OpenMP。OpenMP 4.0 早在 2013 年就引入了任务依赖项,因此除 MSVC++ 之外的任何现代编译器都应提供对该功能的支持。
关于c - 函数依赖 openMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64987301/