Parall...erator(3pm)
π Parall...erator(3pm) β Parallel::Iterator π
okay bestie so this is Parallel::Iterator(3pm) from the User Contributed Perl Documentation, and it's genuinely one of those modules that feels like magic the first time it clicks. Let's get into it π
β¨ NAME β¨
Parallel::Iterator β Simple parallel execution. That's it. That's the whole vibe. π¦
πΈ SYNOPSIS πΈ
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;
}
Lowkey the "map" function applies a user supplied transformation function to each element in a list, returning a new list containing the transformed elements. Like a regular map but it went to the gym πͺ
π¦ DESCRIPTION π¦
This module hands you a 'parallel map'. Multiple worker processes get forked so that so many instances of your transformation function can run at the same time. It's giving group project where everyone actually does their part for once π
For time consuming operations β especially the ones that spend most of their time just waiting on I/O β this is a big performance win. It also gives you a cute little idiom for actually making use of multi CPU systems instead of letting all those cores sit there unbothered. β¨
but fr fr, there's 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. That's why the comment calls it "a very expensive way" β the module is being honest with you π
π MANUAL π
π Basic Usage π
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 URL and returns its contents or undef if it can't be fetched:
sub fetch {
my ($id, $url) = @_;
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 β plot twist β it returns both the index and the value of each element in the array. And here's the important part bestie: because multiple instances of the transformation function execute in parallel, the results won't necessarily come back in order. The array index is the whole reason we can later put completed items in the correct place in an output array. Iconic design choice, no notes π
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. Slay. π
π§ Simpler interfaces π§
Having to construct an iterator is a pain so "iterate" 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 );
β How It Works β
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 STDIN, STDOUT and STDERR are unaffected. π«Ά
Input values are serialised (using Storable) and passed to the workers. Completed work items are serialised and returned. That's the whole loop β pack it up, ship it out, bring it back. π¦
π Caveats π
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. This is the part where you read carefully, bestie. π
π 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. The way that your variable justβ¦ didn't update? Yeah. π
In general you should avoid side effects in your worker subroutines. Write it down. Put it on a sticky note. π
π 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. It's nosy like that, it will find the whole friend group π
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 worker waits for I/O The case of fetching web pages is a good example of this. Fetching a page with
LWP::UserAgentmay 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. Don't be that person, we don't do that here π - the worker is CPU intensive and you have multiple cores / CPUs If the worker is doing an expensive calculation you can parallelise that across multiple CPU 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. Not me launching ten forks to add two numbers π
π INTERFACE π
πΈ "iterate( [ $options ], $worker, $iterator )" πΈ
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 "iterate" will convert it internally into a suitable iterator.
If you are doing this you may wish to investigate "iterate_as_hash" and "iterate_as_array". (Spoilers: they're right below, keep reading bestie β¨)
π Options π
A reference to a hash of options may be supplied as the first argument. The following options are supported:
"workers"β The number of concurrent processes to launch. Set this to0to disable forking. Defaults to10on systems that support fork and0(disable forking) on those that do not. π―"nowarn"β Normally"iterate"will issue a warning and fall back to single process mode on systems on which fork is not available. This option supresses that warning. π€«"batch"β 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. π¦β¨
"adaptive"β 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"iterate"to heuristically determine the batch size by setting the"adaptive"option to a numeric value.
The batch size will be computed as
<number of items seen> / <number of workers> / <adaptive>
A larger value for "adaptive" 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 );
"onerror"β 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'. π (dramatic but that's the default, bestie)
π "iterate_as_array" π
As "iterate" 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 );
π "iterate_as_hash" π
As "iterate" 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 );
π BUGS AND LIMITATIONS π
No bugs have been reported. Periodt. β¨
Please report any bugs or feature requests to "bug-parallel-iterator@rt.cpan.org", or through the web interface at <http://rt.cpan.org>.
π«Ά THANKS π«Ά
Shoutout to Aristotle Pagaltzis, who came through with the suggestion and the patch for the END handling. Not all heroes wear capes, some of them just submit patches that make your cleanup logic behave. πβ¨
π AUTHOR π
Andy Armstrong wrote this whole thing, and you can reach him at andy@hexten.net. π Go say hi, he made your parallel iteration cute and painless.
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2007 by Andy Armstrong. Respect the legacy, bestie. π
It's free software, which means you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. So like, go forth and remix, just keep it free. That's the deal. π€β¨
Okay that's the whole page, we made it to the end, I'm so proud of you. π₯Ήπ
Signing off from perl v5.34.0, dated 2022-08-12 β this was Parall...erator(3pm), and yes the name is abbreviated because apparently we're mysterious like that. πΈπ¦ Go write some worker functions, bestie, you've got this. π«Άπ
π¦ where this page comes from
- debian bookworm: libparallel-iterator-perl 1.002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libparallel-iterator-perl 1.002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libparallel-iterator-perl 1.002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libparallel-iterator-perl 1.002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libparallel-iterator-perl 1.002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms