more useful options PerlMonks

### Re^2: [OT]: threading recursive subroutines.

by ikegami (Pope)
 on Feb 02, 2011 at 21:21 UTC ( #885856=note: print w/replies, xml ) Need Help??

Turned out that using closures, while providing a simple design, actually caused the problem. The design below still needs work because it passes closures around, but it works in concept as shown by the Coro implementation below. (It probably defies the point to use Coro, but it's easier to prototype using it.)

use strict; use warnings; use Engine qw( ); use constant NUM_WORKERS => 4; sub fibonacci_task { my (\$engine, \$on_complete, \$n) = @_; return \$on_complete->(0) if \$n == 0; return \$on_complete->(1) if \$n == 1; my (\$x,\$y); \$engine->process_group( sub { \$on_complete->(\$x+\$y) }, [ \&fibonacci_task => (sub { \$x = \$_[0] }, \$n-2) ], [ \&fibonacci_task => (sub { \$y = \$_[0] }, \$n-1) ], ); } sub fibonacci { my (\$engine, \$n) = @_; my \$result; \$engine->process_and_wait( \&fibonacci_task => ( sub { \$result = \$_[0] }, \$n ) ); return \$result; } { my \$engine = Engine->new(NUM_WORKERS); printf("%s! = %s\n", \$_, fibonacci(\$engine, \$_)) for 1..10; }
1! = 1 2! = 1 3! = 2 4! = 3 5! = 5 6! = 8 7! = 13 8! = 21 9! = 34 10! = 55

The following belongs at the top of the above script:

Create A New User
Node Status?
node history
Node Type: note [id://885856]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2017-12-16 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What programming language do you hate the most?

Results (449 votes). Check out past polls.

Notices?