Intel TBB中的任务延续

Task continuations in Intel TBB

本文关键字:任务 延续 TBB Intel      更新时间:2023-10-16

在TBB中是否有类似PPL的任务延续?我知道低级TBB方法手动分配tbb::task和手动分配延续任务,并手动管理它们的ref计数:

struct FibContinuation: public task {
    long* const sum;
    long x, y;
    FibContinuation( long* sum_ ) : sum(sum_) {}
    task* execute() {
        *sum = x+y;
        return NULL;
    }
};
struct FibTask: public task {
    const long n;
    long* const sum;
    FibTask( long n_, long* sum_ ) :
        n(n_), sum(sum_)
    {}
    task* execute() {
        if( n<CutOff ) {
            *sum = SerialFib(n);
            return NULL;
        } else {
            // long x, y; This line removed 
            FibContinuation& c = 
                *new( allocate_continuation() ) FibContinuation(sum);
            FibTask& a = *new( c.allocate_child() ) FibTask(n-2,&c.x);
            FibTask& b = *new( c.allocate_child() ) FibTask(n-1,&c.y);
            // Set ref_count to "two children plus one for the wait".
            c.set_ref_count(2);
            spawn( b );
            spawn( a );
        // *sum = x+y; This line removed
            return NULL;
        }
    }
};

那简直太可怕了。你必须事先知道你将生成多少子任务,并手动设置适当的引用计数。这是非常脆弱的代码…

PPL指定延续的方式非常简单:

create_task([]()->bool
{
  // compute something then return a bool result
  return true
}).then([](bool aComputedResult)
{
  // do something with aComputedResult
});

你如何在TBB中实现这一点?

是的,有几种推荐的TBB延续样式,您可以在http://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/catalog_of_recommended_task_patterns.htm上阅读。然而,通过TBB库的设计,它们都没有使用像您的PPL示例那样的c++ 11结构。

如果你的问题真的是"TBB是否有用于任务延续的c++ 11接口",那么答案是"没有"。"

没有什么直接的,我在我的博客上发布了一个关于如何使用task_group(它在tbb中)的例子。

语法类似,但不是100%相同,因为它是在任务存在之前发布的。

void SimpleContinuation()
{
    auto task1 = run_task([](){ContinueableTask(1);});
    //task 2 depends on task 1
    auto task2 = run_when(task1, [](){ContinueableTask(2);});
    wait_for_all(task1, task2);
}