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

标签 c++ multithreading parallel-processing tbb

我遇到了下面的 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(虽然,仍然是低效的斐波那契算法)看起来像这样:

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

关于c++ - 计算斐波那契数的一般 tbb 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268035/

相关文章:

c++ - Visual Studio 给出了关于模棱两可的 ctor 的错误

c++ - 如何为 C 链接列表制作 C++ 包装器

c++ - 如何指定要链接到哪个版本的 boost 库?

java - Java 监视器的等待集是否优先于入口集?

c++ - 嵌套锁(关键部分)不起作用

powershell - 如何在 ScriptBlock 中传递 $_ ($PSItem)

c++ - 使用 MPI 进行并行编程以使用动态二维数组进行矩阵乘法时如何解决问题?

c++ - 移动构造函数绕过复制构造函数

java - Eclipse 中的线程自动停止(卡住)

go - 如何始终从 Go channel 获取最新值?