5% assure discount from here only

Wednesday, June 1, 2011

(28) How to use ForkManager in perl code?

Solution:

This post is to demonstrate how to use Parallel::ForkManager, a simple and powerful Perl module available from CPAN that can be used to perform a series of operations in parallel within a single Perl script.

You need to instantiate the ForkManager with the "new" constructor. You must specify the maximum number of processes to be created. If you specify 0, then NO fork will be done; this is good for debugging purposes.

use strict;
use Parallel::ForkManager;

# set a number of maximum process you want to run
my $max_procs = 3;

my @names = qw( print online show );
# hash to resolve PID's back to child specific information

my $pm = new Parallel::ForkManager($max_procs);

# Setup a callback for when a child finishes up so we can
# get it's exit code
$pm->run_on_finish(
sub { my ($pid, $exit_code, $ident) = @_;
print "** $ident just got out of the pool ".
"with PID $pid and exit code: $exit_code\n";
}
);

$pm->run_on_start(
sub { my ($pid,$ident)=@_;
if($ident eq 'print'){
my $a = results(1);
print $a."\n";
}elsif($ident eq 'online'){
my $b = online(2);
print $b."\n";
}else{
my $c = show(3);
print $c."\n";
}
}
);

$pm->run_on_wait(
sub {
print "** Have to wait for one children ...\n"
},
0.5
);

foreach my $child ( 0 .. $#names ) {
my $pid = $pm->start($names[$child]) and next;
$pm->finish($child); # pass an exit code to finish
}

print "Waiting for Children...\n";
$pm->wait_all_children;
print "Everybody is out of the pool!\n";

sub results{
my $process1 = shift;
return "Process number is $process1\n";
}

sub online{
my $process2 = shift;
return "Process number is $process2\n";
}

sub show{
my $process3 = shift;
return "Process number is $process3\n";
}

Do not use Parallel::ForkManager in an environment, where other child processes can affect the run of the main program, so using this module is not recommended in an environment where fork() / wait() is already used.