Simple parallel execution
This document describes Parallel::Iterator version 1.00
use Parallel::Iterator qw( iterate ); # A very expensive way to double 100 numbers... my @nums = ( 1 .. 100 ); my $iter = iterate( sub { my ( $id, $job ) = @_; return $job * 2; }, \@nums ); my @out = (); while ( my ( $index, $value ) = $iter->() ) { $out[$index] = $value; }
The \*(C`map\*(C' function applies a user supplied transformation function to each element in a list, returning a new list containing the transformed elements.
This module provides a 'parallel map'. Multiple worker processes are forked so that many instances of the transformation function may be executed simultaneously.
For time consuming operations, particularly operations that spend most of their time waiting for I/O, this is a big performance win. It also provides a simple idiom to make effective use of multi \s-1CPU\s0 systems.
There is, however, a considerable overhead associated with forking, so the example in the synopsis (doubling a list of numbers) is not a sensible use of this module.
Imagine you have an array of URLs to fetch:
my @urls = qw( http://google.com/ http://hexten.net/ http://search.cpan.org/ ... and lots more ... );
Write a function that retrieves a \s-1URL\s0 and returns its contents or undef if it can't be fetched:
sub fetch { my $url = shift; my $resp = $ua->get($url); return unless $resp->is_success; return $resp->content; };
Now write a function to synthesize a special kind of iterator:
sub list_iter { my @ar = @_; my $pos = 0; return sub { return if $pos >= @ar; my @r = ( $pos, $ar[$pos] ); # Note: returns ( index, value ) $pos++; return @r; }; }
The returned iterator will return each element of the array in turn and then undef. Actually it returns both the index and the value of each element in the array. Because multiple instances of the transformation function execute in parallel the results won't necessarily come back in order. The array index will later allow us to put completed items in the correct place in an output array.
Get an iterator for the list of URLs:
my $url_iter = list_iter( @urls );
Then wrap it in another iterator which will return the transformed results:
my $page_iter = iterate( \&fetch, $url_iter );
Finally loop over the returned iterator storing results:
my @out = ( ); while ( my ( $index, $value ) = $page_iter->() ) { $out[$index] = $value; }
Behind the scenes your program forked into ten (by default) instances of itself and executed the page requests in parallel.
Having to construct an iterator is a pain so \*(C`iterate\*(C' is smart enough to do that for you. Instead of passing an iterator just pass a reference to the array:
my $page_iter = iterate( \&fetch, \@urls );
If you pass a hash reference the iterator you get back will return key, value pairs:
my $some_iter = iterate( \&fetch, \%some_hash );
If the returned iterator is inconvenient you can get back a hash or array instead:
my @done = iterate_as_array( \&fetch, @urls );
my %done = iterate_as_hash( \&worker, %jobs );
The current process is forked once for each worker. Each forked child is connected to the parent by a pair of pipes. The child's \s-1STDIN\s0, \s-1STDOUT\s0 and \s-1STDERR\s0 are unaffected.
Input values are serialised (using Storable) and passed to the workers. Completed work items are serialised and returned.
Parallel::Iterator is designed to be simple to use - but the underlying forking of the main process can cause mystifying problems unless you have an understanding of what is going on behind the scenes.
Worker execution enviroment
All code apart from the worker subroutine executes in the parent process as normal. The worker executes in a forked instance of the parent process. That means that things like this won't work as expected:
my %tally = (); my @r = iterate_as_array( sub { my ($id, $name) = @_; $tally{$name}++; # might not do what you think it does return reverse $name; }, @names );
# Now print out the tally... while ( my ( $name, $count ) = each %tally ) { printf("%5d : %s\n", $count, $name); }
Because the worker is a closure it can see the %tally hash from its enclosing scope; but because it's running in a forked clone of the parent process it modifies its own copy of %tally rather than the copy for the parent process.
That means that after the job terminates the %tally in the parent process will be empty.
In general you should avoid side effects in your worker subroutines.
Serialization
Values are serialised using Storable to pass to the worker subroutine and results from the worker are again serialised before being passed back. Be careful what your values refer to: everything has to be serialised. If there's an indirect way to reach a large object graph Storable will find it and performance will suffer.
To find out how large your serialised values are serialise one of them and check its size:
use Storable qw( freeze ); my $serialized = freeze $some_obj; print length($serialized), " bytes\n";
In your tests you may wish to guard against the possibility of a change to the structure of your values resulting in a sudden increase in serialized size:
ok length(freeze $some_obj) < 1000, "Object too bulky?";
See the documetation for Storable for other caveats.
Performance
Process forking is expensive. Only use Parallel::Iterator in cases where:
The case of fetching web pages is a good example of this. Fetching a page with LWP::UserAgent may take as long as a few seconds but probably consumes only a few milliseconds of processor time. Running many requests in parallel is a huge win - but be kind to the server you're talking to: don't launch a lot of parallel requests unless it's your server or you know it can handle the load.
If the worker is doing an expensive calculation you can parallelise that across multiple \s-1CPU\s0 cores. Benchmark first though. There's a considerable overhead associated with Parallel::Iterator; unless your calculations are time consuming that overhead will dwarf whatever time they take.
Get an iterator that applies the supplied transformation function to each value returned by the input iterator.
Instead of an iterator you may pass an array or hash reference and \*(C`iterate\*(C' will convert it internally into a suitable iterator.
If you are doing this you may wish to investigate \*(C`iterate_as_hash\*(C' and \*(C`iterate_as_array\*(C'.
Options
A reference to a hash of options may be supplied as the first argument. The following options are supported: The number of concurrent processes to launch. Set this to 0 to disable forking. Defaults to 10 on systems that support fork and 0 (disable forking) on those that do not. Normally \*(C`iterate\*(C' will issue a warning and fall back to single process mode on systems on which fork is not available. This option supresses that warning. Ordinarily items are passed to the worker one at a time. If you are processing a large number of items it may be more efficient to process them in batches. Specify the batch size using this option. Batching is transparent from the caller's perspective. Internally it modifies the iterators and worker (by wrapping them in additional closures) so that they pack, process and unpack chunks of work. Extending the idea of batching a number of work items to amortize the overhead of passing work to and from parallel workers you may also ask \*(C`iterate\*(C' to heuristically determine the batch size by setting the \*(C`adaptive\*(C' option to a numeric value. The batch size will be computed as <number of items seen> / <number of workers> / <adaptive> A larger value for \*(C`adaptive\*(C' will reduce the rate at which the batch size increases. Good values tend to be in the range 1 to 2. You can also specify lower and, optionally, upper bounds on the batch size by passing an reference to an array containing ( lower bound, growth ratio, upper bound ). The upper bound may be omitted. my $iter = iterate( { adaptive => [ 5, 2, 100 ] }, $worker, \@stuff ); The action to take when an error is thrown in the iterator. Possible values are 'die', 'warn' or a reference to a subroutine that will be called with the index of the job that threw the exception and the value of $@ thrown. iterate( { onerror => sub { my ($id, $err) = @_; $self->log( "Error for index $id: $err" ); }, $worker, \@jobs ); The default is 'die'. As \*(C`iterate\*(C' but instead of returning an iterator returns an array containing the collected output from the iterator. In a scalar context returns a reference to the same array.
For this to work properly the input iterator must return (index, value) pairs. This allows the results to be placed in the correct slots in the output array. The simplest way to do this is to pass an array reference as the input iterator:
my @output = iterate_as_array( \&some_handler, \@input ); As \*(C`iterate\*(C' but instead of returning an iterator returns a hash containing the collected output from the iterator. In a scalar context returns a reference to the same hash.
For this to work properly the input iterator must return (key, value) pairs. This allows the results to be placed in the correct slots in the output hash. The simplest way to do this is to pass a hash reference as the input iterator:
my %output = iterate_as_hash( \&some_handler, \%input );
Parallel::Iterator requires no configuration files or environment variables.
None.
None reported.
No bugs have been reported.
Please report any bugs or feature requests to \*(C`[email protected]\*(C', or through the web interface at <http://rt.cpan.org>.
Andy Armstrong \*(C`<[email protected]>\*(C'
Aristotle Pagaltzis for the \s-1END\s0 handling suggestion and patch.
Copyright (c) 2007, Andy Armstrong \*(C`<[email protected]>\*(C'. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
\s-1BECAUSE\s0 \s-1THIS\s0 \s-1SOFTWARE\s0 \s-1IS\s0 \s-1LICENSED\s0 \s-1FREE\s0 \s-1OF\s0 \s-1CHARGE\s0, \s-1THERE\s0 \s-1IS\s0 \s-1NO\s0 \s-1WARRANTY\s0 \s-1FOR\s0 \s-1THE\s0 \s-1SOFTWARE\s0, \s-1TO\s0 \s-1THE\s0 \s-1EXTENT\s0 \s-1PERMITTED\s0 \s-1BY\s0 \s-1APPLICABLE\s0 \s-1LAW\s0. \s-1EXCEPT\s0 \s-1WHEN\s0 \s-1OTHERWISE\s0 \s-1STATED\s0 \s-1IN\s0 \s-1WRITING\s0 \s-1THE\s0 \s-1COPYRIGHT\s0 \s-1HOLDERS\s0 \s-1AND/OR\s0 \s-1OTHER\s0 \s-1PARTIES\s0 \s-1PROVIDE\s0 \s-1THE\s0 \s-1SOFTWARE\s0 \*(L"\s-1AS\s0 \s-1IS\s0\*(R" \s-1WITHOUT\s0 \s-1WARRANTY\s0 \s-1OF\s0 \s-1ANY\s0 \s-1KIND\s0, \s-1EITHER\s0 \s-1EXPRESSED\s0 \s-1OR\s0 \s-1IMPLIED\s0, \s-1INCLUDING\s0, \s-1BUT\s0 \s-1NOT\s0 \s-1LIMITED\s0 \s-1TO\s0, \s-1THE\s0 \s-1IMPLIED\s0 \s-1WARRANTIES\s0 \s-1OF\s0 \s-1MERCHANTABILITY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