计算斐波那契数的一般tbb问题
general tbb issue for calculating fibonacci numbers
我发现下面的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;
}
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 静态联系Intel TBB的问题
- 从多线程.net应用程序调用的本机dll中的tbb存在问题
- 链接英特尔 TBB 库时出现问题
- tbb::flow::图的函数对象中嵌套对象的问题
- 英特尔Tbb开销问题
- 计算斐波那契数的一般tbb问题