## Help with Fibonacci Recursive Beginner
211 Views

Hi anyone can help me? why it's not running?

#include <stdio.h>
#include <tbb/tbb.h>

using namespace tbb;

public:
const long n;
long* const sum;
FibTask(long n_,long* sum_ ) : n(n_), sum(sum_)
{}

long x, y;
FibTask& a = *new( allocate_child() )
FibTask& b = *new( allocate_child() )
set_ref_count(3);
spawn( b );
spawn_and_wait_for_all( a );
*sum = x+y;

return NULL;
}
};

long ParallelFib(long n ) {
long sum;

return sum;
}

// Fibonacci paralelo.
int    main() {

long int n = 30;
init.initialize();
printf("%ld",ParallelFib(n));
init.terminate();

return 0;
}

5 Replies Beginner
211 Views

ooops,

#include <stdio.h>
#include <tbb/tbb.h>

using namespace tbb;

public:
const long n;
long* const sum;
FibTask(long n_,long* sum_ ) : n(n_), sum(sum_)
{}

long x, y;
FibTask& a = *new( allocate_child() )
FibTask& b = *new( allocate_child() )
set_ref_count(3);
spawn( b );
spawn_and_wait_for_all( a );
*sum = x+y;

return NULL;
}
};

long ParallelFib(long n ) {
long sum;

return sum;
}

// Fibonacci paralelo.
int    main() {

long int n = 30;
init.initialize();
ParallelFib(n);
init.terminate();

return 0;
} Beginner
211 Views

Segmentation falt Black Belt
211 Views

You don't terminate the calculation. The User Guide does so by delegating the calculation to SerialFib below Cutoff, and SerialFib returns n below 2: 0, 1, … You can eliminate SerialFib, but not the special treatment below n=2. Beginner
211 Views

Thank's Raf,

Now it works!

the final version is

#include <stdio.h>
#include <tbb/tbb.h>

using namespace tbb;

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

public:
const long n;
long* const sum;
FibTask(long n_,long* sum_ ) : n(n_), sum(sum_)
{}
if ( n < 2) {
*sum = SerialFib(n);
} else {
long x, y;
set_ref_count(3);
spawn( b );
spawn_and_wait_for_all( a );
*sum = x+y;
}
return NULL;
}
};

long ParallelFib(long n ) {
long sum;

return sum;
}

// Fibonacci paralelo.
int    main() {

init.initialize();
printf("%ld",ParallelFib(40));
init.terminate();

return 0;
}

It's right isn't it? Black Belt
211 Views

Except that you shouldn't switch to SerialFib only for n smaller than 2 (now you might as well return n instead and get rid of SerialFib). The role of SerialFib in the User Guide example is to give at least tasks at the lower levels enough work that average parallel overhead, even with tasks already orders of magnitude cheaper than threads, remains limited. Here it dominates because no task has more than a few instructions of useful work. See "User Guide>Parallelizing Simple Loops>parallel_for>Controlling Chunking" for a nice explanation of the principle. 