Intel TBB中的任务继续。

4

是否有类似于PPL任务连续性的TBB方法呢? 我熟悉TBB的底层方法,手动分配并手动分配连续任务,并手动管理它们的引用计数:

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中实现这一点?

1
只是一些随机的想法。Boost futures 有 then,我认为自 1.53 以来,可能并没有实现所有方法,而其他一些方法可能存在一些错误。请查看文档。TBB 没有类似的东西,最接近的是 TBB 流程图。您可以为消息创建流程图,TBB 将在可能的情况下并行化。虽然这不像 then 那么简单,但它也更加强大。最后,我想提到的是,TBB 不是专注于基于任务的并行性,而是专注于抽象数据并行问题的算法模式。 - Stephan Dollberg
这个问题比较了两种不同语言方言的实现,并抱怨其中一个存在问题特定细节的脆弱性,而另一个则没有。TBB示例可以在新增-增量-生成循环两次,现在脆弱性已经消失了。可能还有更有效的spawn_all()或其他方法! - mabraham
2个回答

5

2

直接没有什么可做的,我曾在我的博客这里发布了使用task_group(位于tbb中)实现此功能的示例。

语法类似但不完全相同,因为它是在task存在之前发布的。

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);
}

它并没有回答关于TBB的情况。TBB没有'run_task'和'run_when'方法。 - Anton
抱歉,我没有意识到这些函数是在您的博客中在task_group之上实现的。 - Anton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接