c++fibonaccicilk

What is the right way to compute Fibonacci using cilk?


While I'm learning cilk, I countered with 2 opposite examples:

  1. From intel

  2. from wiki (or other examples in the net):

The oppposite lies on those 2 lines:

x = spawn fib (n-1);
y = spawn fib (n-2);

The first site says:

You do not need to add a cilk_spawn attribute to the second recursive call to fib() because that will create an empty continuation

  1. I dont understand why?
  2. What is the right way? (using 2 spawn commands or just one ? )

Solution

  • The code from intel document "int x = cilk_spawn fib(n-1);" asks for permission to run it in another threat, while the next line of "int y = fib(n-2);" will be run on the same threat as the main program. The wiki code asks for a new threat also for computing fib(n-2) so that if there are more than three processors to run the main progran (fib(n)), fib (n-1) and fib(n-2) all on seperate threats.

    Both codes will perform the same if there were only two processors. The following is from the wiki page:

    ... A processor is not obligated to assign a spawned procedure elsewhere; if the machine only has two processors and the second is still busy on fib(1) when the processor executing fib(2) gets to the procedure call, the first processor will suspend fib(2) and execute fib(0) itself, as it would if it were the only processor. Of course, if another processor is available, then it will be called into service, and all three processors would be executing separate frames simultaneously.