in reply to My First POE - Simple Parallel Programming
Below you can find a program to get you started (read the comments).
It uses POE::Wheel::Run which means that if forks your functions like they would be some programs, collects their STDOUT and the sums it up.
Please note that TIMTOWTDI applies to POE as well ;-) so there are other ways to achieve the same purpose. i.e. look into POE::Filter::Reference for passing data between processes etc.
use strict; use warnings; use POE qw(Wheel::Run); POE::Session->create ( inline_states => { _start => \&start, stdout => \&stdout, done => \&done, }, heap => { sum => 0 } # here your sum will endup ); POE::Kernel->run(); exit; sub start{ my ( $kernel, $heap ) = @_[KERNEL, HEAP]; # If you have more functions with similar interface, just create a + loop my $function = POE::Wheel::Run->new( Program => sub { Function_1( 10 ) }, StdoutEvent => 'stdout', CloseEvent => 'done', ); $heap->{function}->{ $function->ID } = $function; $function = POE::Wheel::Run->new( Program => sub { Function_2( 10 ) }, StdoutEvent => 'stdout', CloseEvent => 'done', ); # store the wheel, so that its refcount is incremented $heap->{function}->{ $function->ID } = $function; } sub stdout { my ($heap, $result ) = @_[HEAP, ARG0]; $heap->{sum}+=$result; } sub done{ my ( $kernel, $heap, $function_id ) = @_[ KERNEL, HEAP, ARG0 ]; # delete the reference to the function that has ended, so it may b +e garbage # collected delete $heap->{function}->{$function_id}; # No more childs, print the total amount # alternately you could send a message back to a parent session wi +th the # result if ( scalar( keys( %{$heap->{function}})) == 0 ){ print "RESULT: ", $heap->{sum},"\n"; } } # The STDOUT of your function is "caught" and returned sub Function_1 { my $up_bound1 = shift; my $total_f1; foreach my $in (0..$up_bound1) { $total_f1 += $in/3; } print "$total_f1\n"; return $total_f1; } sub Function_2 { my $up_bound2 = shift; my $total_f2; foreach my $in (0 .. $up_bound2) { $total_f2 += $in; } print "$total_f2\n"; return $total_f2; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: My First POE - Simple Parallel Programming
by Ultra (Hermit) on Feb 01, 2006 at 06:28 UTC |