我遇到了下面的 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/