in reply to How do I run subroutines in parallel?
#!/usr/bin/perl #For afork, the first argument is an array - a child will be #forked for each array element. The second argument indicates the maxi +mum #number of children that may be alive at one time. The third argument +is a #code reference; this is the code that will be executed by the child. +One #argument will be given to this code fragment. For afork, the array el +ement is #passed. Note that this code will assume no other children will be spa +wned, #and that $SIG {CHLD} hasn't been set to IGNORE. #by Abigail if ($#ARGV < 0){@ARGV = qw( 1 2 3 4 5)} afork (\@ARGV,10,\&hello); print "Main says: All done now\n"; sub hello{ my $data = $_[0]; print "hello world from $data\n";} ################################################## sub afork (\@$&) { my ($data, $max, $code) = @_; my $c = 0; foreach my $data (@$data) { wait unless ++ $c <= $max; die "Fork failed: $!\n" unless defined (my $pid = fork); exit $code -> ($data) unless $pid; } 1 until -1 == wait; } #####################################################
|
|---|