int serial_fib( int n) { if( n < 2) return n; else return serial_fib( n - 1) + serial_fib( n - 2); }
int parallel_fib( int n, int cutof) { if ( n < cutof) return serial_fib( n); else { BOOST_ASSERT( boost::this_task::runs_in_pool() ); tsk::task< int > t1( parallel_fib, n - 1, cutof); tsk::task< int > t2( parallel_fib, n - 2, cutof); tsk::handle< int > h1( tsk::async( boost::move( t1), tsk::as_sub_task() ) ) ; tsk::handle< int > h2( tsk::async( boost::move( t2), tsk::as_sub_task() ) ); return h1.get() + h2.get(); } }
void operator()()const { // the result of this task, will be either set directly if < cutoff, otherwise when taks is ready boost::asynchronous::continuation_result<long> task_res = this_task_result(); if (n_<cutoff_) { // n < cutoff => execute ourselves task_res.set_value(serial_fib(n_)); } else { // n> cutoff, create 2 new tasks and when both are done, set our result (res(task1) + res(task2)) boost::asynchronous::create_continuation_job<boost::asynchronous::any_serializable>( // called when subtasks are done, set our result [task_res](std::tuple<boost::future<long>,boost::future<long> > res) { long r = std::get<0>(res).get() + std::get<1>(res).get(); task_res.set_value(r); }, // recursive tasks fib_task(n_-1,cutoff_), fib_task(n_-2,cutoff_)); } }
long serial_fib( T n ) { if( n<2 ) return n; else return serial_fib(n-1)+serial_fib(n-2); }