gpt4 book ai didi

c++ - "final"指令的 "task"子句是否正确?

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:30 25 4
gpt4 key购买 nike

我正在尝试了解如何制作 final task 的条款实际上有效,我在 this 中找到了以下代码示例链接。

#include <stdio.h>
#include <omp.h>

#define THRESHOLD 5

int fib(int n)
{
int i, j;

if (n<2)
return n;

#pragma omp task shared(i) firstprivate(n) final(n <= THRESHOLD)
i=fib(n-1);

#pragma omp task shared(j) firstprivate(n) final(n <= THRESHOLD)
j=fib(n-2);

#pragma omp taskwait
return i+j;
}


int main()
{
int n = 30;
omp_set_dynamic(0);
omp_set_num_threads(4);

#pragma omp parallel shared(n)
{
#pragma omp single
printf ("fib(%d) = %d\n", n, fib(n));
}
}

但是当我检查 n 的值时通过调试,我注意到即使在条件 n <= THRESHOLD 时,递归函数显然仍在被调用。是真的。所以,我的问题是,是我误解了什么还是代码有问题?

最佳答案

当您调用 final 时发生的事情是,从这个任务中派生出来的任务不会从中创建一个新任务。

来自 Specification :

[§ 2.10.1 task Construct] When a final clause is present on a task construct and the final clause expression evaluates to true, the generated task will be a final task. All task constructs encountered during execution of a final task will generate final and included tasks. Note that the use of a variable in a final clause expression of a task construct causes an implicit reference to the variable in all enclosing constructs.

最后的任务是:

A task that forces all of its child tasks to become final and included tasks.

包含的任务是:

A task for which execution is sequentially included in the generating task region. That is, an included task is undeferred and executed immediately by the encountering thread.

在您的情况下,这意味着:如果在此任务中满足 THREASHOLD,则会生成 n-1n-2 生成的新任务,并且不会生成这些任务递归调用时的新任务,但仍然以“老式”函数调用方式调用函数。

关于c++ - "final"指令的 "task"子句是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com