计算斐波那契数的一般tbb问题

general tbb issue for calculating fibonacci numbers

本文关键字:tbb 问题 计算      更新时间:2023-10-16

我发现下面的tbb模板是一个基于任务的编程示例,用于计算c++中的斐波那契数之和。但当我运行它时,我得到了1717986912的值,这不可能是事实。输出应该是3。我做错了什么?

  class FibTask: public task 
  {
public:
const long n;
long * const sum;
FibTask( long n_, long* sum_ ) : n(n_), sum(sum_) {}
    task* execute( )
    { 
        // Overrides virtual function task::execute
    if( n < 0) 
    {
        return 0;
    } 
    else 
    {
        long x, y;
        FibTask& a = *new( allocate_child( ) ) FibTask(n-1,&x);
        FibTask& b = *new( allocate_child( ) ) FibTask(n-2,&y);
        // Set ref_count to "two children plus one for the wait".
        set_ref_count(3);
        // Start b running.
        spawn( b );
        // Start a running and wait for all children (a and b).
        spawn_and_wait_for_all( a );
        // Do the sum
        *sum = x+y;
    }
        return NULL;
}
long ParallelFib( long n ) 
{
    long sum;
    FibTask& a = *new(task::allocate_root( )) FibTask(n,&sum);
    task::spawn_root_and_wait(a);
    return sum;
}
  };

    long main(int argc, char** argv)
{
    FibTask * obj = new FibTask(3,0);
    long b = obj->ParallelFib(3);
    std::cout << b;
    return 0;
 }

这里的截止线很乱。它必须至少为2。例如:

if( n<2 ) {
    *sum = n;
    return NULL;
}

原始示例也使用SerialFib,如下所示http://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Simple_Example_Fibonacci_Numbers.htm

如果不调用SerialFib(),使用低效阻塞式技术计算斐波那契数的低效方法将更加低效。

警告:请注意,此示例仅用于演示此特定的低级别TBB API和此特定的使用方式。除非您确实确定为什么要这样做,否则不打算重复使用。

现代高级API(尽管如此,仍然适用于低效的Fibonacci算法)看起来是这样的:

int Fib(int n) {
    if( n<CUTOFF ) { // 2 is minimum
        return fibSerial(n);
    } else {
        int x, y;
        tbb::parallel_invoke([&]{x=Fib(n-1);}, [&]{y=Fib(n-2);});
        return x+y;
    }
}