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_childrenis blocking, which isn’t very useful. You could use arun_on_startmethod to register each process in a hash and arun_on_finishmethod 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
finishcall, which would look something like:which actually works.