blib/lib/Parallel/Iterator.pm

filter: Statementstmt 92.7% 178 / 192 Branchbran 80.2% 77 / 96 Conditioncond 89.6% 26 / 29 MC/DCmcdc 84.2% 16 / 19 Subroutinesub 100% 29 / 29 Podpod 100% 3 / 3 totaltotal 89.4% 329 / 368 SCAR 42.7
CC
65
Cov
89%
__ANON__
30.4
iterate
13.4
__ANON__
7.0
CRAP 71.2
↑ Summary Build »
1 # $Id: Iterator.pm 2746 2007-10-19 16:36:50Z andy $
2 package Parallel::Iterator;
3  
4 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use Storable qw( store_fd fd_retrieve dclone );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 9 require 5.008;
13  
14 9 our $VERSION = '1.00';
15 9 ▶use base qw( Exporter );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 our @EXPORT_OK = qw( iterate iterate_as_array iterate_as_hash );
17  
18 9 ▶use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ );
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 my %DEFAULTS = (
21 9 ▶ workers => ( ( $Config{d_fork} && !IS_WIN32 ) ? 10 : 0 ),
Branch: 1 branch
BranchTrueFalseTotal
$Parallel::Iterator::Config{'d_fork'} && !&IS_WIN32() ? : 5 4 9
Condition66%2/3
$Parallel::Iterator::Config{"d_fork"} and not &IS_WIN32()
!ll&&!rl&&r
405
MC/DC50%1/2
$Parallel::Iterator::Config{"d_fork"} and not &IS_WIN32()
$Parallel::Iterator::Config{"d_fork"} not &IS_WIN32()
Truth table66%2/3
A and not(B)
A= $Parallel::Iterator::Config{"d_fork"}B= not &IS_WIN32()
ABresult
0X0
100
111
22 onerror => 'die',
23 nowarn => 0,
24 batch => 1,
25 adaptive => 0,
26 );
27  
28 =head1 NAME
29  
30 Parallel::Iterator - Simple parallel execution
31  
32 =head1 VERSION
33  
34 This document describes Parallel::Iterator version 1.00
35  
36 =head1 SYNOPSIS
37  
38 use Parallel::Iterator qw( iterate );
39  
40 # A very expensive way to double 100 numbers...
41
42 my @nums = ( 1 .. 100 );
43
44 my $iter = iterate( sub {
45 my ( $id, $job ) = @_;
46 return $job * 2;
47 }, \@nums );
48
49 my @out = ();
50 while ( my ( $index, $value ) = $iter->() ) {
51 $out[$index] = $value;
52 }
53
54 =head1 DESCRIPTION
55  
56 The C<map> function applies a user supplied transformation function to
57 each element in a list, returning a new list containing the
58 transformed elements.
59  
60 This module provides a 'parallel map'. Multiple worker processes are
61 forked so that many instances of the transformation function may be
62 executed simultaneously.
63  
64 For time consuming operations, particularly operations that spend most
65 of their time waiting for I/O, this is a big performance win. It also
66 provides a simple idiom to make effective use of multi CPU systems.
67  
68 There is, however, a considerable overhead associated with forking, so
69 the example in the synopsis (doubling a list of numbers) is I<not> a
70 sensible use of this module.
71  
72 =head2 Example
73  
74 Imagine you have an array of URLs to fetch:
75  
76 my @urls = qw(
77 http://google.com/
78 http://hexten.net/
79 http://search.cpan.org/
80 ... and lots more ...
81 );
82  
83 Write a function that retrieves a URL and returns its contents or undef
84 if it can't be fetched:
85  
86 sub fetch {
87 my $url = shift;
88 my $resp = $ua->get($url);
89 return unless $resp->is_success;
90 return $resp->content;
91 };
92  
93 Now write a function to synthesize a special kind of iterator:
94  
95 sub list_iter {
96 my @ar = @_;
97 my $pos = 0;
98 return sub {
99 return if $pos >= @ar;
100 my @r = ( $pos, $ar[$pos] ); # Note: returns ( index, value )
101 $pos++;
102 return @r;
103 };
104 }
105  
106 The returned iterator will return each element of the array in turn and
107 then undef. Actually it returns both the index I<and> the value of each
108 element in the array. Because multiple instances of the transformation
109 function execute in parallel the results won't necessarily come back in
110 order. The array index will later allow us to put completed items in the
111 correct place in an output array.
112  
113 Get an iterator for the list of URLs:
114  
115 my $url_iter = list_iter( @urls );
116  
117 Then wrap it in another iterator which will return the transformed results:
118  
119 my $page_iter = iterate( \&fetch, $url_iter );
120  
121 Finally loop over the returned iterator storing results:
122  
123 my @out = ( );
124 while ( my ( $index, $value ) = $page_iter->() ) {
125 $out[$index] = $value;
126 }
127  
128 Behind the scenes your program forked into ten (by default) instances of
129 itself and executed the page requests in parallel.
130  
131 =head2 Simpler interfaces
132  
133 Having to construct an iterator is a pain so C<iterate> is smart enough
134 to do that for you. Instead of passing an iterator just pass a reference
135 to the array:
136  
137 my $page_iter = iterate( \&fetch, \@urls );
138  
139 If you pass a hash reference the iterator you get back will return key,
140 value pairs:
141  
142 my $some_iter = iterate( \&fetch, \%some_hash );
143  
144 If the returned iterator is inconvenient you can get back a hash or
145 array instead:
146  
147 my @done = iterate_as_array( \&fetch, @urls );
148  
149 my %done = iterate_as_hash( \&worker, %jobs );
150  
151 =head2 How It Works
152  
153 The current process is forked once for each worker. Each forked child is
154 connected to the parent by a pair of pipes. The child's STDIN, STDOUT
155 and STDERR are unaffected.
156  
157 Input values are serialised (using Storable) and passed to the workers.
158 Completed work items are serialised and returned.
159  
160 =head2 Caveats
161  
162 Parallel::Iterator is designed to be simple to use - but the underlying
163 forking of the main process can cause mystifying problems unless you
164 have an understanding of what is going on behind the scenes.
165  
166 =head3 Worker execution enviroment
167  
168 All code apart from the worker subroutine executes in the parent process
169 as normal. The worker executes in a forked instance of the parent
170 process. That means that things like this won't work as expected:
171  
172 my %tally = ();
173 my @r = iterate_as_array( sub {
174 my ($id, $name) = @_;
175 $tally{$name}++; # might not do what you think it does
176 return reverse $name;
177 }, @names );
178  
179 # Now print out the tally...
180 while ( my ( $name, $count ) = each %tally ) {
181 printf("%5d : %s\n", $count, $name);
182 }
183  
184 Because the worker is a closure it can see the C<%tally> hash from its
185 enclosing scope; but because it's running in a forked clone of the parent
186 process it modifies its own copy of C<%tally> rather than the copy for
187 the parent process.
188  
189 That means that after the job terminates the C<%tally> in the parent
190 process will be empty.
191  
192 In general you should avoid side effects in your worker subroutines.
193  
194 =head3 Serialization
195  
196 Values are serialised using L<Storable> to pass to the worker subroutine
197 and results from the worker are again serialised before being passed
198 back. Be careful what your values refer to: everything has to be
199 serialised. If there's an indirect way to reach a large object graph
200 Storable will find it and performance will suffer.
201  
202 To find out how large your serialised values are serialise one of them
203 and check its size:
204  
205 use Storable qw( freeze );
206 my $serialized = freeze $some_obj;
207 print length($serialized), " bytes\n";
208  
209 In your tests you may wish to guard against the possibility of a change
210 to the structure of your values resulting in a sudden increase in
211 serialized size:
212  
213 ok length(freeze $some_obj) < 1000, "Object too bulky?";
214  
215 See the documetation for L<Storable> for other caveats.
216  
217 =head3 Performance
218  
219 Process forking is expensive. Only use Parallel::Iterator in cases where:
220  
221 =over
222  
223 =item the worker waits for I/O
224  
225 The case of fetching web pages is a good example of this. Fetching a
226 page with LWP::UserAgent may take as long as a few seconds but probably
227 consumes only a few milliseconds of processor time. Running many
228 requests in parallel is a huge win - but be kind to the server you're
229 talking to: don't launch a lot of parallel requests unless it's your
230 server or you know it can handle the load.
231  
232 =item the worker is CPU intensive and you have multiple cores / CPUs
233  
234 If the worker is doing an expensive calculation you can parallelise that
235 across multiple CPU cores. Benchmark first though. There's a
236 considerable overhead associated with Parallel::Iterator; unless your
237 calculations are time consuming that overhead will dwarf whatever time
238 they take.
239  
240 =back
241  
242 =head1 INTERFACE
243  
244 =head2 C<< iterate( [ $options ], $worker, $iterator ) >>
245  
246 Get an iterator that applies the supplied transformation function to
247 each value returned by the input iterator.
248  
249 Instead of an iterator you may pass an array or hash reference and
250 C<iterate> will convert it internally into a suitable iterator.
251  
252 If you are doing this you may wish to investigate C<iterate_as_hash> and
253 C<iterate_as_array>.
254  
255 =head3 Options
256  
257 A reference to a hash of options may be supplied as the first argument.
258 The following options are supported:
259  
260 =over
261  
262 =item C<workers>
263  
264 The number of concurrent processes to launch. Set this to 0 to disable
265 forking. Defaults to 10 on systems that support fork and 0 (disable
266 forking) on those that do not.
267  
268 =item C<nowarn>
269  
270 Normally C<iterate> will issue a warning and fall back to single process
271 mode on systems on which fork is not available. This option supresses
272 that warning.
273  
274 =item C<batch>
275  
276 Ordinarily items are passed to the worker one at a time. If you are
277 processing a large number of items it may be more efficient to process
278 them in batches. Specify the batch size using this option.
279  
280 Batching is transparent from the caller's perspective. Internally it
281 modifies the iterators and worker (by wrapping them in additional
282 closures) so that they pack, process and unpack chunks of work.
283  
284 =item C<adaptive>
285  
286 Extending the idea of batching a number of work items to amortize the
287 overhead of passing work to and from parallel workers you may also ask
288 C<iterate> to heuristically determine the batch size by setting the
289 C<adaptive> option to a numeric value.
290  
291 The batch size will be computed as
292  
293 <number of items seen> / <number of workers> / <adaptive>
294  
295 A larger value for C<adaptive> will reduce the rate at which the batch
296 size increases. Good values tend to be in the range 1 to 2.
297  
298 You can also specify lower and, optionally, upper bounds on the batch
299 size by passing an reference to an array containing ( lower bound,
300 growth ratio, upper bound ). The upper bound may be omitted.
301  
302 my $iter = iterate(
303 { adaptive => [ 5, 2, 100 ] },
304 $worker, \@stuff );
305  
306 =item C<onerror>
307  
308 The action to take when an error is thrown in the iterator. Possible
309 values are 'die', 'warn' or a reference to a subroutine that will be
310 called with the index of the job that threw the exception and the value
311 of C<$@> thrown.
312  
313 iterate( {
314 onerror => sub {
315 my ($id, $err) = @_;
316 $self->log( "Error for index $id: $err" );
317 },
318 $worker,
319 \@jobs
320 );
321  
322 The default is 'die'.
323
324 =back
325  
326 =cut
327  
328 sub _massage_iterator {
329 27 ▶ my $iter = shift;
Subroutine _massage_iterator: called CC=4 SCAR=13.9
330 27 ▶ if ( 'ARRAY' eq ref $iter ) {
Branch: 3 branches
BranchTrueFalseTotal
if ('ARRAY' eq ref $iter) { } 21 6 27
elsif ('HASH' eq ref $iter) { } 2 4 6
elsif ('CODE' eq ref $iter) { } 4 0 4
331 21 my @ar = @$iter;
332 21 my $pos = 0;
333 return sub {
334 50202 ▶ return if $pos >= @ar;
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $pos >= @ar 76 50126 50202
335 50126 my @r = ( $pos, $ar[$pos] );
336 50126 $pos++;
337 50126 return @r;
338 21 };
339 }
340 elsif ( 'HASH' eq ref $iter ) {
341 2 my %h = %$iter;
342 2 my @k = keys %h;
343 return sub {
344 12 ▶ return unless @k;
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless @k 2 10 12
345 10 my $k = shift @k;
346 10 return ( $k, $h{$k} );
347 2 };
348 }
349 elsif ( 'CODE' eq ref $iter ) {
350 4 return $iter;
351 }
352 else {
353 0 croak "Iterator must be a code, array or hash ref";
354 }
355 }
356  
357 sub _nonfork {
358 9 ▶ my ( $options, $worker, $iter ) = @_;
Subroutine _nonfork: called CC=1 SCAR=0.0
359  
360 return sub {
361 551 ▶ while ( 1 ) {
Subroutine __ANON__: called CC=5 SCAR=16.3
362 551 ▶ if ( my @next = $iter->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@next) = &$iter()) { } 542 9 551
363 542 my ( $id, $work ) = @next;
364 # dclone so that we have the same semantics as the
365 # forked version.
366 542 ▶ $work = dclone $work if defined $work && ref $work;
Branch: 1 branch
BranchTrueFalseTotal
if defined $work and ref $work 424 118 542
Condition66%2/3
defined $work and ref $work
!ll&&!rl&&r
0118424
MC/DC50%1/2
defined $work and ref $work
defined $work ref $work
Truth table66%2/3
A and B
A= defined $workB= ref $work
ABresult
0X0
100
111
367 542 my $result = eval { $worker->( $id, $work ) };
368 542 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) { } 0 542 542
369 0 $options->{onerror}->( $id, $err );
370 }
371 else {
372 542 return ( $id, $result );
373 }
374 }
375 else {
376 9 return;
377 }
378 }
379 9 };
380 }
381  
382 # Does this sub look a bit long to you? :)
383 sub _fork {
384 18 ▶ my ( $options, $worker, $iter ) = @_;
Subroutine _fork: called CC=1 SCAR=0.1
385  
386 18 my @workers = ();
387 18 my @result_queue = ();
388 18 my $select = IO::Select->new;
389 18 my $rotate = 0;
390  
391 return sub {
392 LOOP: {
393 # Make new workers
394 946 ▶ while ( @workers < $options->{workers} && ( my @next = $iter->() ) )
Subroutine __ANON__: called CC=23 SCAR=34.1
Branch: 1 branch
BranchTrueFalseTotal
if (@workers < $options->{"workers"} and my(@next) = &$iter()) 76 1323 1399
Condition100%3/3
@workers < $options->{"workers"} and my(@next) = &$iter()
!ll&&!rl&&r
1322176
MC/DC100%2/2
@workers < $options->{"workers"} and my(@next) = &$iter()
@workers < $options->{"workers"} my(@next) = &$iter()
Truth table100%3/3
A and B
A= @workers < $options->{"workers"}B= my(@next) = &$iter()
ABresult
0X0
100
111
395 {
396  
397 76 my ( $my_rdr, $my_wtr, $child_rdr, $child_wtr )
398 = map IO::Handle->new, 1 .. 4;
399  
400 76 ▶ pipe $child_rdr, $my_wtr
Branch: 1 branch
BranchTrueFalseTotal
pipe $child_rdr, $my_wtr or croak("Can't open write pipe ($!)\n") 0 76 76
401 or croak "Can't open write pipe ($!)\n";
402  
403 76 ▶ pipe $my_rdr, $child_wtr
Branch: 1 branch
BranchTrueFalseTotal
pipe $my_rdr, $child_wtr or croak("Can't open read pipe ($!)\n") 0 76 76
404 or croak "Can't open read pipe ($!)\n";
405  
406 76 ▶ if ( my $pid = fork ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = fork) { } 76 0 76
407 # Parent
408 76 close $_ for $child_rdr, $child_wtr;
409 76 push @workers, $pid;
410 76 $select->add( [ $my_rdr, $my_wtr, 0 ] );
411 76 _put_obj( \@next, $my_wtr );
412 }
413 else {
414 # Child
415 0 close $_ for $my_rdr, $my_wtr;
416  
417 # Don't execute any END blocks
418 9 ▶ use POSIX '_exit';
Subroutine BEGIN: called CC=1 SCAR=0.0
419 0 eval q{END { _exit 0 }};
420  
421 # Worker loop
422 0 ▶ while ( defined( my $job = _get_obj( $child_rdr ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $job = _get_obj($child_rdr))) 0 0 0
423 0 my $result = eval { $worker->( @$job ) };
424 0 my $err = $@;
425 0 ▶ _put_obj(
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 0 0 0
426 [
427 $err
428 ? ( 'E', $job->[0], $err )
429 : ( 'R', $job->[0], $result )
430 ],
431 $child_wtr
432 );
433 }
434  
435 # End of stream
436 0 _put_obj( undef, $child_wtr );
437 0 close $_ for $child_rdr, $child_wtr;
438 # We use CORE::exit for MP compatibility
439 0 CORE::exit;
440 }
441 }
442  
443 1323 ▶ return @{ shift @result_queue } if @result_queue;
Branch: 1 branch
BranchTrueFalseTotal
if @result_queue 928 395 1323
444 395 ▶ if ( $select->count ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($select->count) 378 17 395
445 378 eval {
446 378 my @rdr = $select->can_read;
447 # Anybody got completed work?
448 378 for my $r ( @rdr ) {
449 1014 my ( $rh, $wh, $eof ) = @$r;
450 1014 ▶ if ( defined( my $results = _get_obj( $rh ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $results = _get_obj($rh))) { } 939 75 1014
451 939 my $type = shift @$results;
452 939 ▶ if ( $type eq 'R' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'R') { } 928 11 939
elsif ($type eq 'E') { } 11 0 11
453 928 push @result_queue, $results;
454 }
455 elsif ( $type eq 'E' ) {
456 11 $options->{onerror}->( @$results );
457 }
458 else {
459 0 die "Bad result type: $type";
460 }
461  
462 # We operate a strict one in, one out policy
463 # - which avoids deadlocks. Having received
464 # the previous result send a new work value.
465 938 ▶ unless ( $eof ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($eof) 938 0 938
466 938 ▶ if ( my @next = $iter->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@next) = &$iter()) { } 863 75 938
467 863 _put_obj( \@next, $wh );
468 }
469 else {
470 75 _put_obj( undef, $wh );
471 75 close $wh;
472 75 @{$r}[ 1, 2 ] = ( undef, 1 );
473 }
474 }
475 }
476 else {
477 75 $select->remove( $r );
478 75 close $rh;
479 }
480 }
481 };
482  
483 378 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 1 377 378
484 # Finish all the workers
485 1 _put_obj( undef, $_->[1] ) for $select->handles;
486  
487 # And wait for them to exit
488 1 waitpid( $_, 0 ) for @workers;
489  
490 # Rethrow
491 1 die $err;
492 }
493  
494 377 redo LOOP;
495 }
496 17 waitpid( $_, 0 ) for @workers;
497 17 return;
498 }
499 18 };
500 }
501  
502 sub _batch_input_iter {
503 10 ▶ my ( $code, $options ) = @_;
Subroutine _batch_input_iter: called CC=6 SCAR=17.9
504  
505 10 ▶ if ( my $adapt = $options->{adaptive} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $adapt = $options->{'adaptive'}) { } 6 4 10
506 6 ▶ my $workers = $options->{workers} || 1;
Condition100%2/2
$options->{'workers'} || 1
l!l
33
MC/DC100%1/1
$options->{'workers'} || 1
$options->{'workers'}
Truth table100%2/2
A
A= $options->{'workers'}
Aresult
11
00
507 6 my $count = 0;
508  
509 6 ▶ $adapt = [ 1, $adapt, undef ]
Branch: 1 branch
BranchTrueFalseTotal
unless "ARRAY" eq ref $adapt 4 2 6
510 unless 'ARRAY' eq ref $adapt;
511  
512 6 my ( $min, $ratio, $max ) = @$adapt;
513 6 ▶ $min = 1 unless defined $min && $min > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min and $min > 1 4 2 6
Condition66%2/3
defined $min and $min > 1
!ll&&!rl&&r
042
MC/DC50%1/2
defined $min and $min > 1
defined $min $min > 1
Truth table66%2/3
A and B
A= defined $minB= $min > 1
ABresult
0X0
100
111
514  
515 return sub {
516 774 ▶ my @chunk = ();
Subroutine __ANON__: called CC=7 SCAR=19.5
517  
518 # Adapt batch size
519 774 my $batch = $count / $workers / $ratio;
520 774 ▶ $batch = $min if $batch < $min;
Branch: 1 branch
BranchTrueFalseTotal
if $batch < $min 44 730 774
521 774 ▶ $batch = $max if defined $max && $batch > $max;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max and $batch > $max 499 275 774
Condition100%3/3
defined $max and $batch > $max
!ll&&!rl&&r
25421499
MC/DC100%2/2
defined $max and $batch > $max
defined $max $batch > $max
Truth table100%3/3
A and B
A= defined $maxB= $batch > $max
ABresult
0X0
100
111
522  
523 774 ▶ while ( @chunk < $batch && ( my @next = $code->() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@chunk < $batch and my(@next) = &$code()) 30000 774 30774
Condition100%3/3
@chunk < $batch and my(@next) = &$code()
!ll&&!rl&&r
7363830000
MC/DC100%2/2
@chunk < $batch and my(@next) = &$code()
@chunk < $batch my(@next) = &$code()
Truth table100%3/3
A and B
A= @chunk < $batchB= my(@next) = &$code()
ABresult
0X0
100
111
524 30000 push @chunk, \@next;
525 30000 $count++;
526 }
527  
528 774 ▶ return @chunk ? ( 0, \@chunk ) : ();
Branch: 1 branch
BranchTrueFalseTotal
@chunk ? : 741 33 774
529 6 };
530 }
531 else {
532 4 my $batch = $options->{batch};
533  
534 return sub {
535 226 ▶ my @chunk = ();
Subroutine __ANON__: called CC=4 SCAR=13.9
536 226 ▶ while ( @chunk < $batch && ( my @next = $code->() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@chunk < $batch and my(@next) = &$code()) 20000 226 20226
Condition100%3/3
@chunk < $batch and my(@next) = &$code()
!ll&&!rl&&r
2022420000
MC/DC100%2/2
@chunk < $batch and my(@next) = &$code()
@chunk < $batch my(@next) = &$code()
Truth table100%3/3
A and B
A= @chunk < $batchB= my(@next) = &$code()
ABresult
0X0
100
111
537 20000 push @chunk, \@next;
538 }
539 226 ▶ return @chunk ? ( 0, \@chunk ) : ();
Branch: 1 branch
BranchTrueFalseTotal
@chunk ? : 204 22 226
540 4 };
541 }
542 }
543  
544 sub _batch_output_iter {
545 10 ▶ my $code = shift;
Subroutine _batch_output_iter: called CC=1 SCAR=0.0
546 10 my @queue = ();
547 return sub {
548 50010 ▶ unless ( @queue ) {
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
unless (@queue) 955 49055 50010
549 955 ▶ if ( my ( undef, $chunk ) = $code->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $chunk) = &$code()) { } 945 10 955
550 945 @queue = @$chunk;
551 }
552 else {
553 10 return;
554 }
555 }
556 50000 return @{ shift @queue };
557 10 };
558 0 return $code;
559 }
560  
561 sub _batch_worker {
562 10 ▶ my $code = shift;
Subroutine _batch_worker: called CC=1 SCAR=0.0
563 return sub {
564 388 ▶ my ( undef, $chunk ) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
565 388 for my $item ( @$chunk ) {
566 25000 $item->[1] = $code->( @$item );
567 }
568 388 return $chunk;
569 10 };
570 }
571  
572 sub iterate {
573 27 ▶ my %options = ( %DEFAULTS, %{ 'HASH' eq ref $_[0] ? shift : {} } );
Subroutine iterate: called CC=13 SCAR=26.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
'HASH' eq ref $_[0] ? : 27 0 27
574  
575 27 ▶ croak "iterate takes 2 or 3 args" unless @_ == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 2 0 27 27
576  
577 27 my @bad_opt = grep { !exists $DEFAULTS{$_} } keys %options;
578 27 ▶ croak "Unknown option(s): ", join( ', ', sort @bad_opt ), "\n"
Branch: 1 branch
BranchTrueFalseTotal
if @bad_opt 0 27 27
579 if @bad_opt;
580  
581 27 my $worker = shift;
582 27 ▶ croak "Worker must be a coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless "CODE" eq ref $worker 0 27 27
583 unless 'CODE' eq ref $worker;
584  
585 27 my $iter = _massage_iterator( shift );
586  
587 27 ▶ if ( $options{onerror} =~ /^(die|warn)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"onerror"} =~ /^(die|warn)$/) 26 1 27
588 26 $options{onerror} = eval "sub { shift; $1 shift }";
589 }
590  
591 croak "onerror option must be 'die', 'warn' or a code reference"
592 27 ▶ unless 'CODE' eq ref $options{onerror};
Branch: 1 branch
BranchTrueFalseTotal
unless "CODE" eq ref $options{"onerror"} 0 27 27
593  
594 27 ▶ if ( $options{workers} > 0 && $DEFAULTS{workers} == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"workers"} > 0 and $DEFAULTS{"workers"} == 0) 3 24 27
Condition100%3/3
$options{"workers"} > 0 and $DEFAULTS{"workers"} == 0
!ll&&!rl&&r
6183
MC/DC100%2/2
$options{"workers"} > 0 and $DEFAULTS{"workers"} == 0
$options{"workers"} > 0 $DEFAULTS{"workers"} == 0
Truth table100%3/3
A and B
A= $options{"workers"} > 0B= $DEFAULTS{"workers"} == 0
ABresult
0X0
100
111
595 warn "Fork not available; falling back to single process mode\n"
596 3 ▶ unless $options{nowarn};
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"nowarn"} 0 3 3
597 3 $options{workers} = 0;
598 }
599  
600 27 ▶ my $factory = $options{workers} == 0 ? \&_nonfork : \&_fork;
Branch: 1 branch
BranchTrueFalseTotal
$options{'workers'} == 0 ? : 9 18 27
601  
602 27 ▶ if ( $options{batch} > 1 || $options{adaptive} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'batch'} > 1 or $options{'adaptive'}) { } 10 17 27
Condition100%3/3
$options{"batch"} > 1 or $options{"adaptive"}
l!l&&r!l&&!r
4617
MC/DC100%2/2
$options{"batch"} > 1 or $options{"adaptive"}
$options{"batch"} > 1 $options{"adaptive"}
Truth table100%3/3
A or B
A= $options{"batch"} > 1B= $options{"adaptive"}
ABresult
1X1
011
000
603 10 return _batch_output_iter(
604 $factory->(
605 \%options,
606 _batch_worker( $worker ),
607 _batch_input_iter( $iter, \%options )
608 )
609 );
610 }
611 else {
612 # OK. Ready. Let's do it.
613 17 return $factory->( \%options, $worker, $iter );
614 }
615 }
616  
617 =head2 C<< iterate_as_array >>
618  
619 As C<iterate> but instead of returning an iterator returns an array
620 containing the collected output from the iterator. In a scalar context
621 returns a reference to the same array.
622  
623 For this to work properly the input iterator must return (index, value)
624 pairs. This allows the results to be placed in the correct slots in the
625 output array. The simplest way to do this is to pass an array reference
626 as the input iterator:
627  
628 my @output = iterate_as_array( \&some_handler, \@input );
629  
630 =cut
631  
632 sub iterate_as_array {
633 17 ▶ my $iter = iterate( @_ );
Subroutine iterate_as_array: called CC=3 SCAR=11.0
Pod documented
634 17 my @out = ();
635 17 ▶ while ( my ( $index, $value ) = $iter->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$iter()) 50110 17 50127
636 50110 $out[$index] = $value;
637 }
638 17 ▶ return wantarray ? @out : \@out;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 17 0 17
639 }
640  
641 =head2 C<< iterate_as_hash >>
642  
643 As C<iterate> but instead of returning an iterator returns a hash
644 containing the collected output from the iterator. In a scalar context
645 returns a reference to the same hash.
646  
647 For this to work properly the input iterator must return (key, value)
648 pairs. This allows the results to be placed in the correct slots in the
649 output hash. The simplest way to do this is to pass a hash reference as
650 the input iterator:
651  
652 my %output = iterate_as_hash( \&some_handler, \%input );
653  
654 =cut
655  
656 sub iterate_as_hash {
657 1 ▶ my $iter = iterate( @_ );
Subroutine iterate_as_hash: called CC=3 SCAR=11.0
Pod documented
658 1 my %out = ();
659 1 ▶ while ( my ( $key, $value ) = $iter->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$iter()) 5 1 6
660 5 $out{$key} = $value;
661 }
662 1 ▶ return wantarray ? %out : \%out;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 0 1
663 }
664  
665 sub _get_obj {
666 1014 ▶ my $fd = shift;
Subroutine _get_obj: called CC=1 SCAR=0.0
667 1014 my $r = fd_retrieve $fd;
668 1014 return $r->[0];
669 }
670  
671 sub _put_obj {
672 1015 ▶ my ( $obj, $fd ) = @_;
Subroutine _put_obj: called CC=1 SCAR=0.0
673 1015 store_fd [$obj], $fd;
674 1015 $fd->flush;
675 }
676  
677 9 1;
678 __END__
↑ Summary Build »