简体   繁体   中英

Perl Parallel::ForkManager empty return

I am trying to use Parallel::ForkManager to run proceed parallel but unfortunately the subroutine parallel does not return any entries.

 sub parallel {
   my ($self,$values) = @_;
   my %hash;
   my $pm = Parallel::ForkManager->new(200);
   foreach my $IP ( keys %{$values} ) { 
    my $pid = $pm->start and next;
    $hash{$IP}=$self->getData($IP);
    $pm->finish(0, \$hash{$IP});
   }
   $pm->wait_all_children;
   return %hash;
  }



print Dumper( parallel(%data) );

What I'm doing wrong? Any ideas?

Forking is the creation of a new process that's a copy of the current process. Changing a variable in one process doesn't change similarly named variables in other processes.

You modify the child's process's %hash , but you're dumping the parent's process's %hash .

P::FM does provide a mechanism for passing data back to the parent process. It's documented under the heading "RETRIEVING DATASTRUCTURES from child processes".

use Data::Dumper          qw( Dumper );
use Parallel::ForkManager qw( );

use constant MAX_WORKERS => 200;

my %hash;

my $pm = Parallel::ForkManager->new(MAX_WORKERS);
$pm->run_on_finish(sub {
   my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $result_ref) = @_;

   my $IP = $ident;

   warn("Child $IP killed by signal $exit_signal"), return if $exit_signal;
   warn("Child $IP exited with error $exit_code"),  return if $exit_code;
   warn("Child $IP encountered an unknown error"),  return if !$result_ref;

   $hash{$IP} = $$result_ref;
});

for my $IP (keys %$values) { 
   my $pid = $pm->start($IP) and next;
   $pm->finish(0, \$self->getData($IP));
}

$pm->wait_all_children();

print(Dumper(\%hash));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM