Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2464 Discussions

simple fibonacci program segmentation fault

rockingsoul
Beginner
308 Views

Hello,

I am just starting to learn TBB, and I tried to implement a simple Fibonacci number generator program mentioned in the Intel Technology Journal:

http://www.intel.com/technology/itj/2007/v11i4/5-foundations/4-tbb.htm

I just copied and paste the code from the journal page, and made my own MAIN. It compiles, but when I try to run it, it gives me a segmentation fault. The Serial portion of the code works fine. it seems that there is something wrong with the parameter passing, since the execution would not even jump into the execute() function (printf("checkpoint \n") wouldn't print anything in there) I would really, really appreciate if you could point me to the possible direction as what is wrong with the code below. Thanks a lot here first!

/***Fib***/

using namespace std;
using namespace tbb;

int CutOff = 20;

long SerialFib( long n )
{
if ( n<2 )
return n;
else
return SerialFib(n-1) + SerialFib(n-2);
}

///////////////////// Parallel methods ////////////////////////

class FibTask: public task
{
public:
const long n;
long* const sum;

FibTask( long n_, long* sum_ ) : n(n_), sum(sum_) {}
task* execute()
{
printf("checkpoint \n");
if( n {

*sum = SerialFib(n);
}
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(3);
spawn( b );
spawn_and_wait_for_all( a );
*sum = x+y;
}
return NULL;
}
};

long ParallelFib ( long n )
{
long sum;

FibTask& a = *new(task::allocate_root())
FibTask(n, ∑);
task::spawn_root_and_wait(a);

return sum;
}

/////////////////////////// Main ////////////////////////////////////////////////////

//! program entry
int main(int argc, char* argv[])
{
long NumbersCount = argc>1 ? strtol(argv[1],0,0) : 500;
long sum;

printf( "Fib number %d \n", NumbersCount );

sum = ParallelFib ( NumbersCount );
//sum = SerialFib ( NumbersCount );
printf( "Result is %d \n", sum );

return 0;
}

0 Kudos
1 Solution
RafSchietekat
Valued Contributor III
309 Views

In main(), you'll need something like "tbb::task_scheduler_init anonymous;".

View solution in original post

0 Kudos
2 Replies
RafSchietekat
Valued Contributor III
310 Views

In main(), you'll need something like "tbb::task_scheduler_init anonymous;".

0 Kudos
rockingsoul
Beginner
309 Views
Quoting - Raf Schietekat

In main(), you'll need something like "tbb::task_scheduler_init anonymous;".


Thank you Raf, that is it!

0 Kudos
Reply