1Parallel::Iterator(3) User Contributed Perl DocumentationParallel::Iterator(3)
2
3
4
6 Parallel::Iterator - Simple parallel execution
7
9 This document describes Parallel::Iterator version 1.00
10
12 use Parallel::Iterator qw( iterate );
13
14 # A very expensive way to double 100 numbers...
15
16 my @nums = ( 1 .. 100 );
17
18 my $iter = iterate( sub {
19 my ( $id, $job ) = @_;
20 return $job * 2;
21 }, \@nums );
22
23 my @out = ();
24 while ( my ( $index, $value ) = $iter->() ) {
25 $out[$index] = $value;
26 }
27
29 The "map" function applies a user supplied transformation function to
30 each element in a list, returning a new list containing the transformed
31 elements.
32
33 This module provides a 'parallel map'. Multiple worker processes are
34 forked so that many instances of the transformation function may be
35 executed simultaneously.
36
37 For time consuming operations, particularly operations that spend most
38 of their time waiting for I/O, this is a big performance win. It also
39 provides a simple idiom to make effective use of multi CPU systems.
40
41 There is, however, a considerable overhead associated with forking, so
42 the example in the synopsis (doubling a list of numbers) is not a
43 sensible use of this module.
44
45 Example
46 Imagine you have an array of URLs to fetch:
47
48 my @urls = qw(
49 http://google.com/
50 http://hexten.net/
51 http://search.cpan.org/
52 ... and lots more ...
53 );
54
55 Write a function that retrieves a URL and returns its contents or undef
56 if it can't be fetched:
57
58 sub fetch {
59 my $url = shift;
60 my $resp = $ua->get($url);
61 return unless $resp->is_success;
62 return $resp->content;
63 };
64
65 Now write a function to synthesize a special kind of iterator:
66
67 sub list_iter {
68 my @ar = @_;
69 my $pos = 0;
70 return sub {
71 return if $pos >= @ar;
72 my @r = ( $pos, $ar[$pos] ); # Note: returns ( index, value )
73 $pos++;
74 return @r;
75 };
76 }
77
78 The returned iterator will return each element of the array in turn and
79 then undef. Actually it returns both the index and the value of each
80 element in the array. Because multiple instances of the transformation
81 function execute in parallel the results won't necessarily come back in
82 order. The array index will later allow us to put completed items in
83 the correct place in an output array.
84
85 Get an iterator for the list of URLs:
86
87 my $url_iter = list_iter( @urls );
88
89 Then wrap it in another iterator which will return the transformed
90 results:
91
92 my $page_iter = iterate( \&fetch, $url_iter );
93
94 Finally loop over the returned iterator storing results:
95
96 my @out = ( );
97 while ( my ( $index, $value ) = $page_iter->() ) {
98 $out[$index] = $value;
99 }
100
101 Behind the scenes your program forked into ten (by default) instances
102 of itself and executed the page requests in parallel.
103
104 Simpler interfaces
105 Having to construct an iterator is a pain so "iterate" is smart enough
106 to do that for you. Instead of passing an iterator just pass a
107 reference to the array:
108
109 my $page_iter = iterate( \&fetch, \@urls );
110
111 If you pass a hash reference the iterator you get back will return key,
112 value pairs:
113
114 my $some_iter = iterate( \&fetch, \%some_hash );
115
116 If the returned iterator is inconvenient you can get back a hash or
117 array instead:
118
119 my @done = iterate_as_array( \&fetch, @urls );
120
121 my %done = iterate_as_hash( \&worker, %jobs );
122
123 How It Works
124 The current process is forked once for each worker. Each forked child
125 is connected to the parent by a pair of pipes. The child's STDIN,
126 STDOUT and STDERR are unaffected.
127
128 Input values are serialised (using Storable) and passed to the workers.
129 Completed work items are serialised and returned.
130
131 Caveats
132 Parallel::Iterator is designed to be simple to use - but the underlying
133 forking of the main process can cause mystifying problems unless you
134 have an understanding of what is going on behind the scenes.
135
136 Worker execution enviroment
137
138 All code apart from the worker subroutine executes in the parent
139 process as normal. The worker executes in a forked instance of the
140 parent process. That means that things like this won't work as
141 expected:
142
143 my %tally = ();
144 my @r = iterate_as_array( sub {
145 my ($id, $name) = @_;
146 $tally{$name}++; # might not do what you think it does
147 return reverse $name;
148 }, @names );
149
150 # Now print out the tally...
151 while ( my ( $name, $count ) = each %tally ) {
152 printf("%5d : %s\n", $count, $name);
153 }
154
155 Because the worker is a closure it can see the %tally hash from its
156 enclosing scope; but because it's running in a forked clone of the
157 parent process it modifies its own copy of %tally rather than the copy
158 for the parent process.
159
160 That means that after the job terminates the %tally in the parent
161 process will be empty.
162
163 In general you should avoid side effects in your worker subroutines.
164
165 Serialization
166
167 Values are serialised using Storable to pass to the worker subroutine
168 and results from the worker are again serialised before being passed
169 back. Be careful what your values refer to: everything has to be
170 serialised. If there's an indirect way to reach a large object graph
171 Storable will find it and performance will suffer.
172
173 To find out how large your serialised values are serialise one of them
174 and check its size:
175
176 use Storable qw( freeze );
177 my $serialized = freeze $some_obj;
178 print length($serialized), " bytes\n";
179
180 In your tests you may wish to guard against the possibility of a change
181 to the structure of your values resulting in a sudden increase in
182 serialized size:
183
184 ok length(freeze $some_obj) < 1000, "Object too bulky?";
185
186 See the documetation for Storable for other caveats.
187
188 Performance
189
190 Process forking is expensive. Only use Parallel::Iterator in cases
191 where:
192
193 the worker waits for I/O
194 The case of fetching web pages is a good example of this. Fetching
195 a page with LWP::UserAgent may take as long as a few seconds but
196 probably consumes only a few milliseconds of processor time.
197 Running many requests in parallel is a huge win - but be kind to
198 the server you're talking to: don't launch a lot of parallel
199 requests unless it's your server or you know it can handle the
200 load.
201
202 the worker is CPU intensive and you have multiple cores / CPUs
203 If the worker is doing an expensive calculation you can parallelise
204 that across multiple CPU cores. Benchmark first though. There's a
205 considerable overhead associated with Parallel::Iterator; unless
206 your calculations are time consuming that overhead will dwarf
207 whatever time they take.
208
210 "iterate( [ $options ], $worker, $iterator )"
211 Get an iterator that applies the supplied transformation function to
212 each value returned by the input iterator.
213
214 Instead of an iterator you may pass an array or hash reference and
215 "iterate" will convert it internally into a suitable iterator.
216
217 If you are doing this you may wish to investigate "iterate_as_hash" and
218 "iterate_as_array".
219
220 Options
221
222 A reference to a hash of options may be supplied as the first argument.
223 The following options are supported:
224
225 "workers"
226 The number of concurrent processes to launch. Set this to 0 to
227 disable forking. Defaults to 10 on systems that support fork and 0
228 (disable forking) on those that do not.
229
230 "nowarn"
231 Normally "iterate" will issue a warning and fall back to single
232 process mode on systems on which fork is not available. This option
233 supresses that warning.
234
235 "batch"
236 Ordinarily items are passed to the worker one at a time. If you are
237 processing a large number of items it may be more efficient to
238 process them in batches. Specify the batch size using this option.
239
240 Batching is transparent from the caller's perspective. Internally
241 it modifies the iterators and worker (by wrapping them in
242 additional closures) so that they pack, process and unpack chunks
243 of work.
244
245 "adaptive"
246 Extending the idea of batching a number of work items to amortize
247 the overhead of passing work to and from parallel workers you may
248 also ask "iterate" to heuristically determine the batch size by
249 setting the "adaptive" option to a numeric value.
250
251 The batch size will be computed as
252
253 <number of items seen> / <number of workers> / <adaptive>
254
255 A larger value for "adaptive" will reduce the rate at which the
256 batch size increases. Good values tend to be in the range 1 to 2.
257
258 You can also specify lower and, optionally, upper bounds on the
259 batch size by passing an reference to an array containing ( lower
260 bound, growth ratio, upper bound ). The upper bound may be omitted.
261
262 my $iter = iterate(
263 { adaptive => [ 5, 2, 100 ] },
264 $worker, \@stuff );
265
266 "onerror"
267 The action to take when an error is thrown in the iterator.
268 Possible values are 'die', 'warn' or a reference to a subroutine
269 that will be called with the index of the job that threw the
270 exception and the value of $@ thrown.
271
272 iterate( {
273 onerror => sub {
274 my ($id, $err) = @_;
275 $self->log( "Error for index $id: $err" );
276 },
277 $worker,
278 \@jobs
279 );
280
281 The default is 'die'.
282
283 "iterate_as_array"
284 As "iterate" but instead of returning an iterator returns an array
285 containing the collected output from the iterator. In a scalar context
286 returns a reference to the same array.
287
288 For this to work properly the input iterator must return (index, value)
289 pairs. This allows the results to be placed in the correct slots in the
290 output array. The simplest way to do this is to pass an array reference
291 as the input iterator:
292
293 my @output = iterate_as_array( \&some_handler, \@input );
294
295 "iterate_as_hash"
296 As "iterate" but instead of returning an iterator returns a hash
297 containing the collected output from the iterator. In a scalar context
298 returns a reference to the same hash.
299
300 For this to work properly the input iterator must return (key, value)
301 pairs. This allows the results to be placed in the correct slots in the
302 output hash. The simplest way to do this is to pass a hash reference as
303 the input iterator:
304
305 my %output = iterate_as_hash( \&some_handler, \%input );
306
308 Parallel::Iterator requires no configuration files or environment
309 variables.
310
312 None.
313
315 None reported.
316
318 No bugs have been reported.
319
320 Please report any bugs or feature requests to
321 "bug-parallel-iterator@rt.cpan.org", or through the web interface at
322 <http://rt.cpan.org>.
323
325 Andy Armstrong "<andy@hexten.net>"
326
328 Aristotle Pagaltzis for the END handling suggestion and patch.
329
331 Copyright (c) 2007, Andy Armstrong "<andy@hexten.net>". All rights
332 reserved.
333
334 This module is free software; you can redistribute it and/or modify it
335 under the same terms as Perl itself. See perlartistic.
336
338 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
339 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
340 WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
341 PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
342 EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
343 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
344 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
345 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
346 NECESSARY SERVICING, REPAIR, OR CORRECTION.
347
348 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
349 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
350 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
351 TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
352 CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
353 SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
354 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
355 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
356 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
357 DAMAGES.
358
359
360
361perl v5.32.1 2021-01-27 Parallel::Iterator(3)