开发者

how do I pipe with use Parallel::ForkManager?

开发者 https://www.devze.com 2023-03-18 09:43 出处:网络
I want to have children processes write to the parent\'s @array. I\'ve read about piping but I\'m very confused on how to actually implement it:

I want to have children processes write to the parent's @array. I've read about piping but I'm very confused on how to actually implement it:

use Parallel::ForkManager;
my @array;
my $pm=new Parallel::ForkManager(开发者_开发问答3); 

    for((1..5)){
    $pm->start and next; 
    print "child: ".$_."\n";
    push(@array,$_); # what do I do here to put it into the parent's @array????
    $pm->finish; 
    }
$pm->wait_all_children;


print "parent: ".$_."\n" for @array;


If you want to use pipes, then you need to create a pair of pipes before you spawn each child, write to the writing pipe from the child, and use IO::Select to read from all of the reading ends in parallel in the parent. You'll also need to change the way you wait for the children, since ForkManager's wait_all_children is blocking, which isn't very useful. You could use a run_on_start method to register each process in a hash and a run_on_finish method to delete each process after it dies, and then terminate the select loop when no processes are remaining.

Or, if it's not important that the children can pass their results back to the parent in realtime, you can use ForkManager's ability to pass data back to the parent on exit through the finish call, which would look something like:

#!perl
use strict;
use warnings;
use Parallel::ForkManager;

# No indirect object notation
my $pm = Parallel::ForkManager->new(3);
my @array;
$pm->run_on_finish(sub {
    my $return = $_[5]; # Count 'em.
    push @array, @$return;
});

for(1..5) {
  $pm->start and next;
  print "child: $_\n";
  $pm->finish(0, [$_]);
}

$pm->wait_all_children;

print "parent: $_\n" for @array;

which actually works.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号