Sunday, August 26, 2012

Perl parallel tasks using fork

I am working on a Perl application which needs to do repetitive tasks. As such I am using the mighty fork() - actually to make things easier for myself, I am using the Parallel::ForkManager module. The following piece of code spawns 5 children running as parallel processes:

#!/usr/bin/perl

use strict;
use warnings;
use Parallel::ForkManager;

main();

sub main {

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

  for (my $i=0; $i <= 10; $i++) {
    my $pid = $pm->start and next;
    print "Spawned process $$\n";
    $pm->finish;
  }

  $pm->wait_all_children;
}


Note: The child PID returns 0 inside parent but we can use the $$ special variable to get the PID of the child.
Post a Comment