Advertisement
RieqyNS13

Untitled

Jul 21st, 2012
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 11.63 KB | None | 0 0
  1. =head1 NAME
  2.  
  3. Parallel::ForkManager - A simple parallel processing fork manager
  4.  
  5. =head1 SYNOPSIS
  6.  
  7.   use Parallel::ForkManager;
  8.  
  9.   $pm = new Parallel::ForkManager($MAX_PROCESSES);
  10.  
  11.   foreach $data (@all_data) {
  12.     # Forks and returns the pid for the child:
  13.     my $pid = $pm->start and next;
  14.  
  15.     ... do some work with $data in the child process ...
  16.  
  17.     $pm->finish; # Terminates the child process
  18.   }
  19.  
  20. =head1 DESCRIPTION
  21.  
  22. This module is intended for use in operations that can be done in parallel
  23. where the number of processes to be forked off should be limited. Typical
  24. use is a downloader which will be retrieving hundreds/thousands of files.
  25.  
  26. The code for a downloader would look something like this:
  27.  
  28.   use LWP::Simple;
  29.   use Parallel::ForkManager;
  30.  
  31.   ...
  32.  
  33.   @links=(
  34.     ["http://www.foo.bar/rulez.data","rulez_data.txt"],
  35.     ["http://new.host/more_data.doc","more_data.doc"],
  36.     ...
  37.   );
  38.  
  39.   ...
  40.  
  41.   # Max 30 processes for parallel download
  42.   my $pm = new Parallel::ForkManager(30);
  43.  
  44.   foreach my $linkarray (@links) {
  45.     $pm->start and next; # do the fork
  46.  
  47.     my ($link,$fn) = @$linkarray;
  48.     warn "Cannot get $fn from $link"
  49.       if getstore($link,$fn) != RC_OK;
  50.  
  51.     $pm->finish; # do the exit in the child process
  52.   }
  53.   $pm->wait_all_children;
  54.  
  55. First you need to instantiate the ForkManager with the "new" constructor.
  56. You must specify the maximum number of processes to be created. If you
  57. specify 0, then NO fork will be done; this is good for debugging purposes.
  58.  
  59. Next, use $pm->start to do the fork. $pm returns 0 for the child process,
  60. and child pid for the parent process (see also L<perlfunc(1p)/fork()>).
  61. The "and next" skips the internal loop in the parent process. NOTE:
  62. $pm->start dies if the fork fails.
  63.  
  64. $pm->finish terminates the child process (assuming a fork was done in the
  65. "start").
  66.  
  67. NOTE: You cannot use $pm->start if you are already in the child process.
  68. If you want to manage another set of subprocesses in the child process,
  69. you must instantiate another Parallel::ForkManager object!
  70.  
  71. =head1 METHODS
  72.  
  73. =over 5
  74.  
  75. =item new $processes
  76.  
  77. Instantiate a new Parallel::ForkManager object. You must specify the maximum
  78. number of children to fork off. If you specify 0 (zero), then no children
  79. will be forked. This is intended for debugging purposes.
  80.  
  81. =item start [ $process_identifier ]
  82.  
  83. This method does the fork. It returns the pid of the child process for
  84. the parent, and 0 for the child process. If the $processes parameter
  85. for the constructor is 0 then, assuming you're in the child process,
  86. $pm->start simply returns 0.
  87.  
  88. An optional $process_identifier can be provided to this method... It is used by
  89. the "run_on_finish" callback (see CALLBACKS) for identifying the finished
  90. process.
  91.  
  92. =item finish [ $exit_code ]
  93.  
  94. Closes the child process by exiting and accepts an optional exit code
  95. (default exit code is 0) which can be retrieved in the parent via callback.
  96. If you use the program in debug mode ($processes == 0), this method doesn't
  97. do anything.
  98.  
  99. =item set_max_procs $processes
  100.  
  101. Allows you to set a new maximum number of children to maintain. Returns
  102. the previous setting.
  103.  
  104. =item wait_all_children
  105.  
  106. You can call this method to wait for all the processes which have been
  107. forked. This is a blocking wait.
  108.  
  109. =back
  110.  
  111. =head1 CALLBACKS
  112.  
  113. You can define callbacks in the code, which are called on events like starting
  114. a process or upon finish.
  115.  
  116. The callbacks can be defined with the following methods:
  117.  
  118. =over 4
  119.  
  120. =item run_on_finish $code [, $pid ]
  121.  
  122. You can define a subroutine which is called when a child is terminated. It is
  123. called in the parent process.
  124.  
  125. The paremeters of the $code are the following:
  126.  
  127.   - pid of the process, which is terminated
  128.   - exit code of the program
  129.   - identification of the process (if provided in the "start" method)
  130.   - exit signal (0-127: signal name)
  131.   - core dump (1 if there was core dump at exit)
  132.  
  133. =item run_on_start $code
  134.  
  135. You can define a subroutine which is called when a child is started. It called
  136. after the successful startup of a child in the parent process.
  137.  
  138. The parameters of the $code are the following:
  139.  
  140.   - pid of the process which has been started
  141.   - identification of the process (if provided in the "start" method)
  142.  
  143. =item run_on_wait $code, [$period]
  144.  
  145. You can define a subroutine which is called when the child process needs to wait
  146. for the startup. If $period is not defined, then one call is done per
  147. child. If $period is defined, then $code is called periodically and the
  148. module waits for $period seconds betwen the two calls. Note, $period can be
  149. fractional number also. The exact "$period seconds" is not guarranteed,
  150. signals can shorten and the process scheduler can make it longer (on busy
  151. systems).
  152.  
  153. The $code called in the "start" and the "wait_all_children" method also.
  154.  
  155. No parameters are passed to the $code on the call.
  156.  
  157. =back
  158.  
  159. =head1 EXAMPLE
  160.  
  161. =head2 Parallel get
  162.  
  163. This small example can be used to get URLs in parallel.
  164.  
  165.   use Parallel::ForkManager;
  166.   use LWP::Simple;
  167.   my $pm=new Parallel::ForkManager(10);
  168.   for my $link (@ARGV) {
  169.     $pm->start and next;
  170.     my ($fn)= $link =~ /^.*\/(.*?)$/;
  171.     if (!$fn) {
  172.       warn "Cannot determine filename from $fn\n";
  173.     } else {
  174.       $0.=" ".$fn;
  175.       print "Getting $fn from $link\n";
  176.       my $rc=getstore($link,$fn);
  177.       print "$link downloaded. response code: $rc\n";
  178.     };
  179.     $pm->finish;
  180.   };
  181.  
  182. =head2 Callbacks
  183.  
  184. Example of a program using callbacks to get child exit codes:
  185.  
  186.   use strict;
  187.   use Parallel::ForkManager;
  188.  
  189.   my $max_procs = 5;
  190.   my @names = qw( Fred Jim Lily Steve Jessica Bob Dave Christine Rico Sara );
  191.   # hash to resolve PID's back to child specific information
  192.  
  193.   my $pm =  new Parallel::ForkManager($max_procs);
  194.  
  195.   # Setup a callback for when a child finishes up so we can
  196.   # get it's exit code
  197.   $pm->run_on_finish(
  198.     sub { my ($pid, $exit_code, $ident) = @_;
  199.       print "** $ident just got out of the pool ".
  200.         "with PID $pid and exit code: $exit_code\n";
  201.     }
  202.   );
  203.  
  204.   $pm->run_on_start(
  205.     sub { my ($pid,$ident)=@_;
  206.       print "** $ident started, pid: $pid\n";
  207.     }
  208.   );
  209.  
  210.   $pm->run_on_wait(
  211.     sub {
  212.       print "** Have to wait for one children ...\n"
  213.     },
  214.     0.5
  215.   );
  216.  
  217.   foreach my $child ( 0 .. $#names ) {
  218.     my $pid = $pm->start($names[$child]) and next;
  219.  
  220.     # This code is the child process
  221.     print "This is $names[$child], Child number $child\n";
  222.     sleep ( 2 * $child );
  223.     print "$names[$child], Child $child is about to get out...\n";
  224.     sleep 1;
  225.     $pm->finish($child); # pass an exit code to finish
  226.   }
  227.  
  228.   print "Waiting for Children...\n";
  229.   $pm->wait_all_children;
  230.   print "Everybody is out of the pool!\n";
  231.  
  232. =head1 BUGS AND LIMITATIONS
  233.  
  234. Do not use Parallel::ForkManager in an environment, where other child
  235. processes can affect the run of the main program, so using this module
  236. is not recommended in an environment where fork() / wait() is already used.
  237.  
  238. If you want to use more than one copies of the Parallel::ForkManager, then
  239. you have to make sure that all children processes are terminated, before you
  240. use the second object in the main program.
  241.  
  242. You are free to use a new copy of Parallel::ForkManager in the child
  243. processes, although I don't think it makes sense.
  244.  
  245. =head1 COPYRIGHT
  246.  
  247. Copyright (c) 2000 Szabó, Balázs (dLux)
  248.  
  249. All right reserved. This program is free software; you can redistribute it
  250. and/or modify it under the same terms as Perl itself.
  251.  
  252. =head1 AUTHOR
  253.  
  254.   dLux (Szabó, Balázs) <dlux@kapu.hu>
  255.  
  256. =head1 CREDITS
  257.  
  258.   Noah Robin <sitz@onastick.net> (documentation tweaks)
  259.   Chuck Hirstius <chirstius@megapathdsl.net> (callback exit status, example)
  260.   Grant Hopwood <hopwoodg@valero.com> (win32 port)
  261.   Mark Southern <mark_southern@merck.com> (bugfix)
  262.  
  263. =cut
  264.  
  265. package Parallel::ForkManager;
  266. use POSIX ":sys_wait_h";
  267. use strict;
  268. use vars qw($VERSION);
  269. $VERSION='0.7.5';
  270.  
  271. sub new { my ($c,$processes)=@_;
  272.   my $h={
  273.     max_proc   => $processes,
  274.     processes  => {},
  275.     in_child   => 0,
  276.   };
  277.   return bless($h,ref($c)||$c);
  278. };
  279.  
  280. sub start { my ($s,$identification)=@_;
  281.   die "Cannot start another process while you are in the child process"
  282.     if $s->{in_child};
  283.   while ($s->{max_proc} && ( keys %{ $s->{processes} } ) >= $s->{max_proc}) {
  284.     $s->on_wait;
  285.     $s->wait_one_child(defined $s->{on_wait_period} ? &WNOHANG : undef);
  286.   };
  287.   $s->wait_children;
  288.   if ($s->{max_proc}) {
  289.     my $pid=fork();
  290.     die "Cannot fork: $!" if !defined $pid;
  291.     if ($pid) {
  292.       $s->{processes}->{$pid}=$identification;
  293.       $s->on_start($pid,$identification);
  294.     } else {
  295.       $s->{in_child}=1 if !$pid;
  296.     }
  297.     return $pid;
  298.   } else {
  299.     $s->{processes}->{$$}=$identification;
  300.     $s->on_start($$,$identification);
  301.     return 0; # Simulating the child which returns 0
  302.   }
  303. }
  304.  
  305. sub finish { my ($s, $x)=@_;
  306.   if ( $s->{in_child} ) {
  307.     exit ($x || 0);
  308.   }
  309.   if ($s->{max_proc} == 0) { # max_proc == 0
  310.     $s->on_finish($$, $x ,$s->{processes}->{$$}, 0, 0);
  311.     delete $s->{processes}->{$$};
  312.   }
  313.   return 0;
  314. }
  315.  
  316. sub wait_children { my ($s)=@_;
  317.   return if !keys %{$s->{processes}};
  318.   my $kid;
  319.   do {
  320.     $kid = $s->wait_one_child(&WNOHANG);
  321.   } while $kid > 0 || $kid < -1; # AS 5.6/Win32 returns negative PIDs
  322. };
  323.  
  324. *wait_childs=*wait_children; # compatibility
  325.  
  326. sub wait_one_child { my ($s,$par)=@_;
  327.   my $kid;
  328.   while (1) {
  329.     $kid = $s->_waitpid(-1,$par||=0);
  330.     last if $kid == 0 || $kid == -1; # AS 5.6/Win32 returns negative PIDs
  331.     redo if !exists $s->{processes}->{$kid};
  332.     my $id = delete $s->{processes}->{$kid};
  333.     $s->on_finish( $kid, $? >> 8 , $id, $? & 0x7f, $? & 0x80 ? 1 : 0);
  334.     last;
  335.   }
  336.   $kid;
  337. };
  338.  
  339. sub wait_all_children { my ($s)=@_;
  340.   while (keys %{ $s->{processes} }) {
  341.     $s->on_wait;
  342.     $s->wait_one_child(defined $s->{on_wait_period} ? &WNOHANG : undef);
  343.   };
  344. }
  345.  
  346. *wait_all_childs=*wait_all_children; # compatibility;
  347.  
  348. sub run_on_finish { my ($s,$code,$pid)=@_;
  349.   $s->{on_finish}->{$pid || 0}=$code;
  350. }
  351.  
  352. sub on_finish { my ($s,$pid,@par)=@_;
  353.   my $code=$s->{on_finish}->{$pid} || $s->{on_finish}->{0} or return 0;
  354.   $code->($pid,@par);
  355. };
  356.  
  357. sub run_on_wait { my ($s,$code, $period)=@_;
  358.   $s->{on_wait}=$code;
  359.   $s->{on_wait_period} = $period;
  360. }
  361.  
  362. sub on_wait { my ($s)=@_;
  363.   if(ref($s->{on_wait}) eq 'CODE') {
  364.     $s->{on_wait}->();
  365.     if (defined $s->{on_wait_period}) {
  366.         local $SIG{CHLD} = sub { } if ! defined $SIG{CHLD};
  367.         select undef, undef, undef, $s->{on_wait_period}
  368.     };
  369.   };
  370. };
  371.  
  372. sub run_on_start { my ($s,$code)=@_;
  373.   $s->{on_start}=$code;
  374. }
  375.  
  376. sub on_start { my ($s,@par)=@_;
  377.   $s->{on_start}->(@par) if ref($s->{on_start}) eq 'CODE';
  378. };
  379.  
  380. sub set_max_procs { my ($s, $mp)=@_;
  381.   $s->{max_proc} = $mp;
  382. }
  383.  
  384. # OS dependant code follows...
  385.  
  386. sub _waitpid { # Call waitpid() in the standard Unix fashion.
  387.   return waitpid($_[1],$_[2]);
  388. }
  389.  
  390. # On ActiveState Perl 5.6/Win32 build 625, waitpid(-1, &WNOHANG) always
  391. # blocks unless an actual PID other than -1 is given.
  392. sub _NT_waitpid { my ($s, $pid, $par) = @_;
  393.   if ($par == &WNOHANG) { # Need to nonblock on each of our PIDs in the pool.
  394.     my @pids = keys %{ $s->{processes} };
  395.     # Simulate -1 (no processes awaiting cleanup.)
  396.     return -1 unless scalar(@pids);
  397.     # Check each PID in the pool.
  398.     my $kid;
  399.     foreach $pid (@pids) {
  400.       $kid = waitpid($pid, $par);
  401.       return $kid if $kid != 0; # AS 5.6/Win32 returns negative PIDs.
  402.     }
  403.     return $kid;
  404.   } else { # Normal waitpid() call.
  405.     return waitpid($pid, $par);
  406.   }
  407. }
  408.  
  409. {
  410.   local $^W = 0;
  411.   if ($^O eq 'NT' or $^O eq 'MSWin32') {
  412.     *_waitpid = \&_NT_waitpid;
  413.   }
  414. }
  415.  
  416. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement