Community
cancel
Showing results for
Did you mean:
Highlighted
Beginner
9 Views

## Help with Fibonacci Recursive

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
Highlighted
Beginner
9 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;
}

Highlighted
Beginner
9 Views

Segmentation falt

Highlighted
Black Belt
9 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.

Highlighted
Beginner
9 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?

Highlighted
Black Belt
9 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.