Loops.pm

filter: Statementstmt 92.6% 228 / 246 Branchbran 78.0% 39 / 50 Conditioncond 66.6% 2 / 3 MC/DCmcdc 50.0% 1 / 2 Subroutinesub 80.9% 34 / 42 Podpod 37.5% 3 / 8 totaltotal 87.4% 307 / 351 CC 35 SCAR 16.3
CC
35
Cov
90%
while
13.0
readChangesFromChild
11.3
share
4.0
CRAP 5.1
↑ Summary createTarball.pl »
1 package Parallel::Loops;
2  
3 16 our $VERSION='0.09';
4  
5 # For Tie::ExtraHash - This was the earliest perl version in which I found this
6 # class
7 16 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 Parallel::Loops - Execute loops using parallel forked subprocesses
12  
13 =encoding utf-8
14  
15 =head1 SYNOPSIS
16  
17 use Parallel::Loops;
18  
19 my $maxProcs = 5;
20 my $pl = Parallel::Loops->new($maxProcs);
21  
22 my @parameters = ( 0 .. 9 );
23  
24 # We want to perform some hefty calculation for each @input and
25 # store each calculation's result in %output. For that reason, we
26 # "tie" %output, so that changes to %output in any child process
27 # (see below) are automatically transfered and updated in the
28 # parent also.
29  
30 my %returnValues;
31 $pl->share( \%returnValues );
32  
33 $pl->foreach( \@parameters, sub {
34 # This sub "magically" executed in parallel forked child
35 # processes
36  
37 # Lets just create a simple example, but this could be a
38 # massive calculation that will be parallelized, so that
39 # $maxProcs different processes are calculating sqrt
40 # simultaneously for different values of $_ on different CPUs
41 # (Do see 'Performance' / 'Properties of the loop body' below)
42  
43 $returnValues{$_} = sqrt($_);
44 });
45 foreach (@parameters) {
46 printf "i: %d sqrt(i): %f\n", $_, $returnValues{$_};
47 }
48  
49 You can also use @arrays instead of %hashes, and/or while loops
50 instead of foreach:
51  
52 my @returnValues;
53 $pl->share(\@returnValues);
54  
55 my $i = 0;
56 $pl->while ( sub { $i++ < 10 }, sub {
57 # This sub "magically" executed in parallel forked
58 # child processes
59  
60 push @returnValues, [ $i, sqrt($i) ];
61 });
62  
63 And you can have both foreach and while return values so that $pl->share()
64 isn't required at all:
65  
66 my $maxProcs = 5;
67 my $pl = Parallel::Loops->new($maxProcs);
68 my %returnValues = $pl->foreach( [ 0..9 ], sub {
69 # Again, this is executed in a forked child
70 $_ => sqrt($_);
71 });
72  
73 =head1 DESCRIPTION
74  
75 Often a loop performs calculations where each iteration of the loop
76 does not depend on the previous iteration, and the iterations really
77 could be carried out in any order.
78  
79 This module allows you to run such loops in parallel using all the
80 CPUs at your disposal.
81  
82 Return values are automatically transfered from children to parents via
83 %hashes or @arrays, that have explicitly been configured for that sort
84 of sharing via $pl->share(). Hashes will transfer keys that are
85 set in children (but not cleared or unset), and elements that are
86 pushed to @arrays in children are pushed to the parent @array too (but
87 note that the order is not guaranteed to be the same as it would have
88 been if done all in one process, since there is no way of knowing
89 which child would finish first!)
90  
91 If you can see past the slightly awkward syntax, you're basically
92 getting foreach and while loops that can run in parallel without
93 having to bother with fork, pipes, signals etc. This is all handled
94 for you by this module.
95  
96 =head2 foreach loop
97  
98 $pl->foreach($arrayRef, $childBodySub)
99  
100 Runs $childBodySub->() with $_ set foreach element in @$arrayRef, except that
101 $childBodySub is run in a forked child process to obtain parallelism.
102 Essentially, this does something conceptually similar to:
103  
104 foreach(@$arrayRef) {
105 $childBodySub->();
106 }
107  
108 Any setting of hash keys or pushing to arrays that have been set with
109 $pl->share() will automagically appear in the hash or array in the parent
110 process.
111  
112 If you like loop variables, you can run it like so:
113  
114 $pl->foreach( \@input, sub {
115 my $i = $_;
116 .. bla, bla, bla ... $output{$i} = sqrt($i);
117 }
118 );
119  
120 =head2 while loop
121  
122 $pl->while($conditionSub, $childBodySub [,$finishSub])
123  
124 Essentially, this does something conceptually similar to:
125  
126 while($conditionSub->()) {
127 $childBodySub->();
128 }
129  
130 except that $childBodySub->() is executed in a forked child process.
131 Return values are transfered via share() like in L</foreach loop> above.
132  
133 =head3 While loops must affect condition outside $childBodySub
134  
135 Note that incrementing $i in the $childBodySub like in this example
136 B<will not work>:
137  
138 $pl->while( sub { $i < 5 },
139 sub {
140 $output{$i} = sqrt($i);
141 # Won't work!
142 $i++
143 }
144 );
145  
146 Because $childBodySub is executed in a child, and so while $i would
147 be incremented in the child, that change would not make it to the
148 parent, where $conditionSub is evaluated. The changes that make
149 $conditionSub return false eventually I<must> take place outside
150 the $childBodySub so it is executed in the parent. (Adhering to
151 the parallel principle that one iteration may not affect any other
152 iterations - including whether to run them or not)
153  
154 =head3 Optional $finishSub parameter
155  
156 In order to track progress, an optional C<$finishSub> can be provided. It will
157 be called whenever a child finishes. The return value from the C<$conditionSub>
158 is remembered and provided to the C<$finishSub> as a reference:
159  
160 my $i = 0;
161 my %returnValues = $pl->while (
162 sub { $i++ < 10 ? $i : 0 },
163 sub {
164 return ($i, sqrt($i));
165 },
166 sub {
167 my ($i) = @_;
168 printf "Child %d has finished\n", $i;
169 }
170 );
171  
172 =head2 share
173  
174 $pl->share(\%output, \@output, ...)
175  
176 Each of the arguments to share() are instrumented, so that when a
177 hash key is set or array element pushed in a child, this is transfered
178 to the parent's hash or array automatically when a child is finished.
179  
180 B<Note the limitation> Only keys being set like C<$hash{'key'} = 'value'> and
181 arrays elements being pushed like C<push @array, 'value'> will be transfered to
182 the parent. Unsetting keys, or setting particluar array elements with
183 $array[3]='value' will be lost if done in the children. Also, if two different
184 children set a value for the same key, a random one of them will be seen by the
185 parent.
186  
187 In the parent process all the %hashes and @arrays are full-fledged, and you can
188 use all operations. But only these mentioned operations in the child processes
189 make it back to the parent.
190  
191 =head3 Array element sequence not defined
192  
193 Note that when using share() for @returnValue arrays, the sequence of elements
194 in @returnValue is not guaranteed to be the same as you'd see with a normal
195 sequential while or foreach loop, since the calculations are done in parallel
196 and the children may end in an unexpected sequence. But if you don't really
197 care about the order of elements in the @returnValue array then share-ing an
198 array can be useful and fine.
199  
200 If you need to be able to determine which iteration generated what output, use
201 a hash instead.
202  
203 =head2 Recursive forking is possible
204  
205 Note that no check is performed for recursive forking: If the main
206 process encouters a loop that it executes in parallel, and the
207 execution of the loop in child processes also encounters a parallel
208 loop, these will also be forked, and you'll essentially have
209 $maxProcs^2 running processes. It wouldn't be too hard to implement
210 such a check (either inside or outside this package).
211  
212 =head1 Exception/Error Handling / Dying
213  
214 If you want some measure of exception handling you can use eval in the child
215 like this:
216  
217 my %errors;
218 $pl->share( \%errors );
219 my %returnValues = $pl->foreach( [ 0..9 ], sub {
220 # Again, this is executed in a forked child
221 eval {
222 die "Bogus error"
223 if $_ == 3;
224 $_ => sqrt($_);
225 };
226 if ($@) {
227 $errors{$_} = $@;
228 }
229 });
230  
231 # Now test %errors. $errors{3} should exist as the only element
232  
233 Also, be sure not to call exit() in the child. That will just exit the child
234 and that doesn't work. Right now, exit just makes the parent fail no-so-nicely.
235 Patches to this that handle exit somehow are welcome.
236  
237 =head1 Performance
238  
239 =head2 Properties of the loop body
240  
241 Keep in mind that a child process is forked every time while or foreach calls
242 the provided sub. For use of Parallel::Loops to make sense, each invocation
243 needs to actually do some serious work for the performance gain of parallel
244 execution to outweigh the overhead of forking and communicating between the
245 processes. So while sqrt() in the example above is simple, it will actually be
246 slower than just running it in a standard foreach loop because of the overhead.
247  
248 Also, if each loop sub returns a massive amount of data, this needs to be
249 communicated back to the parent process, and again that could outweigh parallel
250 performance gains unless the loop body does some heavy work too.
251  
252 =head2 Linux and Windows Comparison
253  
254 On the same VMware host, I ran this script in Debian Linux and Windows XP
255 virtual machines respectively. The script runs a "no-op" sub in 1000 child
256 processes two in parallel at a time
257  
258 my $pl = Parallel::Loops->new(2);
259 $pl->foreach( [1..1000], sub {} );
260  
261 For comparison, that took:
262  
263 7.3 seconds on Linux
264 43 seconds on Strawberry Perl for Windows
265 240 seconds on Cygwin for Windows
266  
267 =head2 fork() e.g. on Windows
268  
269 On some platforms the fork() is emulated. Be sure to read perlfork.
270  
271 =head2 Temporary files unless select() works - e.g. on Windows
272  
273 E.g. on Windows, select is only supported for sockets, and not for pipes. So we
274 use temporary files to store the information sent from the child to the parent.
275 This adds a little extra overhead. See perlport for other platforms where there
276 are problems with select. Parallel::Loops tests for a working select() and uses
277 temporary files otherwise.
278  
279 =head1 SEE ALSO
280  
281 This module uses fork(). ithreads could have been possible too, but was not
282 chosen. You may want to check out:
283  
284 When to use forks, when to use threads ...?
285 L<http://www.perlmonks.org/index.pl?node_id=709061>
286  
287 The forks module (not used here)
288 L<http://search.cpan.org/search?query=forks>
289  
290 threads in perlthrtut
291 L<http://perldoc.perl.org/perlthrtut.html>
292  
293 =head1 DEPENDENCIES
294  
295 I believe this is the only dependency that isn't part of core perl:
296  
297 use Parallel::ForkManager;
298  
299 These should all be in perl's core:
300  
301 use Storable;
302 use IO::Handle;
303 use Tie::Array;
304 use Tie::Hash;
305  
306 =head1 BUGS / ENHANCEMENTS
307  
308 No bugs are known at the moment. Send any reports to peter@morch.com.
309  
310 Enhancements:
311  
312 Optionally prevent recursive forking: If a forked child encounters a
313 Parallel::Loop it should be possible to prevent that Parallel::Loop instance to
314 also create forks.
315  
316 Determine the number of CPUs so that new()'s $maxProcs parameter can be
317 optional. Could use e.g. Sys::Sysconf, UNIX::Processors or Sys::CPU.
318  
319 Maybe use function prototypes (see Prototypes under perldoc perlsub).
320  
321 Then we could do something like
322  
323 pl_foreach @input {
324 yada($_);
325 };
326 or
327  
328 pl_foreach $pl @input {
329 yada($_);
330 };
331  
332 instead of
333  
334 $pl->foreach(\@input, sub {
335 yada($_);
336 });
337  
338 and so on, where the first suggestion above means global variables (yikes!).
339 Unfortunately, methods aren't supported by prototypes, so this will never be
340 posssible:
341  
342 $pl->foreach @input {
343 yada($_);
344 };
345  
346 An alternative pointed out by the perlmonks chatterbox could be to use
347 L<Devel::Declare|http://search.cpan.org/perldoc?Devel::Declare> "if I can stand
348 pain".
349  
350 =head1 SOURCE REPOSITORY
351  
352 See the git source on github L<https://github.com/pmorch/perl-Parallel-Loops>
353  
354 =head1 COPYRIGHT
355  
356 Copyright (c) 2008 Peter Valdemar Mørch <peter@morch.com>
357  
358 All right reserved. This program is free software; you can redistribute it
359 and/or modify it under the same terms as Perl itself.
360  
361 =head1 AUTHOR
362  
363 Peter Valdemar Mørch <peter@morch.com>
364  
365 =cut
366  
367 16 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
368 16 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
369  
370 16 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
371 16 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
372 16 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
373 16 ▶use File::Temp qw(tempfile);
Subroutine BEGIN: called CC=1 SCAR=0.0
374 16 ▶use Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
375 16 ▶use Parallel::ForkManager;
Subroutine BEGIN: called CC=1 SCAR=0.0
376  
377 sub new {
378 16 ▶ my ($class, $maxProcs, %options) = @_;
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
379 16 my $self = {
380 maxProcs => $maxProcs,
381 shareNr => 0,
382 workingSelect => testWorkingSelect(),
383 };
384 16 return bless $self, $class;
385 }
386  
387 sub testWorkingSelect {
388 16 ▶ my $reader = IO::Handle->new();
Subroutine testWorkingSelect: called CC=2 SCAR=6.9
Pod undocumented
389 16 my $writer = IO::Handle->new();
390 16 ▶ pipe( $reader, $writer )
Branch: 1 branch
BranchTrueFalseTotal
pipe $reader, $writer or die "Couldn't open a pipe" 0 16 16
391 or die "Couldn't open a pipe";
392 16 $writer->autoflush(1);
393 16 my $select = IO::Select->new();
394 16 $select->add($reader);
395 16 print $writer "test\n";
396  
397 # There should be data right away, so lets not risk blocking if it is
398 # unreliable
399 16 my @handles = $select->can_read(0);
400 16 my $working = (scalar(@handles) == 1);
401  
402 16 close $reader;
403 16 close $writer;
404  
405 16 return $working;
406 }
407  
408 sub share {
409 64 ▶ my ($self, @tieRefs) = @_;
Subroutine share: called CC=4 SCAR=13.9
Pod documented
410 64 foreach my $ref (@tieRefs) {
411 64 ▶ if (ref $ref eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ref eq 'HASH') { } 16 48 64
elsif (ref $ref eq 'ARRAY') { } 16 32 48
412 16 my %initialContents = %$ref;
413 # $storage will point to the Parallel::Loops::TiedHash object
414 16 my $storage;
415 16 tie %$ref, 'Parallel::Loops::TiedHash', $self, \$storage;
416 16 %$ref = %initialContents;
417 16 push @{$$self{tieObjects}}, $storage;
418 16 push @{$$self{tieHashes}}, [$$self{shareNr}, $ref];
419 } elsif (ref $ref eq 'ARRAY') {
420 16 my @initialContents = @$ref;
421 # $storage will point to the Parallel::Loops::TiedArray object
422 16 my $storage;
423 16 tie @$ref, 'Parallel::Loops::TiedArray', $self, \$storage;
424 16 @$ref = @initialContents;
425 16 push @{$$self{tieObjects}}, $storage;
426 16 push @{$$self{tieArrays}}, [$$self{shareNr}, $ref];
427 } else {
428 32 croak "Only unblessed hash and array refs are supported by share";
429 }
430 32 $$self{shareNr}++;
431 }
432 }
433  
434 sub in_child {
435 256 ▶ my ($self) = @_;
Subroutine in_child: called CC=2 SCAR=7.1
Pod undocumented
436 256 ▶ return $$self{forkManager} && $$self{forkManager}->is_child;
Condition66%2/3
$self->{'forkManager'} && $self->{'forkManager'}->is_child
!ll&&!rl&&r
022630
MC/DC50%1/2
$self->{'forkManager'} && $self->{'forkManager'}->is_child
$self->{'forkManager'} $self->{'forkManager'}->is_child
Truth table66%2/3
A && B
A= $self->{'forkManager'}B= $self->{'forkManager'}->is_child
ABresult
0X0
100
111
437 }
438  
439 sub readChangesFromChild {
440 113 ▶ my ($self, $childRdr, $childFinishSub) = @_;
Subroutine readChangesFromChild: called CC=11 SCAR=24.3
Pod undocumented
441  
442 113 my $childOutput;
443  
444 113 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'workingSelect'}) { } 100 13 113
445 100 local $/;
446 100 $childOutput = <$childRdr>;
447 } else {
448 13 my $filename = <$childRdr>;
449 13 ▶ open my $in, $filename
Branch: 1 branch
BranchTrueFalseTotal
open my $in, $filename or die "Couldn't open $filename" 0 13 13
450 or die "Couldn't open $filename";
451 13 binmode $in;
452 {
453 13 local $/;
454 13 $childOutput = <$in>;
455 }
456 13 close $in;
457 13 unlink $filename;
458  
459 }
460 113 ▶ die "Error getting result contents from child"
Branch: 1 branch
BranchTrueFalseTotal
if $childOutput eq "" 0 113 113
461 if $childOutput eq '';
462  
463 113 my @output;
464 113 eval {
465 113 @output = @{ Storable::thaw($childOutput) };
466 };
467 113 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 113 113
468 0 die "Error interpreting result from child: $@";
469 }
470 113 my $error = shift @output;
471 113 my $retval = shift @output;
472  
473 113 foreach my $set (@{$$self{tieHashes}}) {
474 113 my ($outputNr, $h) = @$set;
475 113 foreach my $k (keys %{$output[$outputNr]}) {
476 113 $$h{$k} = $output[$outputNr]{$k};
477 }
478 }
479 113 foreach my $set (@{$$self{tieArrays}}) {
480 113 my ($outputNr, $a) = @$set;
481 113 foreach my $v (@{$output[$outputNr]}) {
482 113 push @$a, $v;
483 }
484 }
485 113 ▶ if ($error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error) 0 113 113
486 0 die "Error from child: $error";
487 }
488 113 ▶ $childFinishSub->()
Branch: 1 branch
BranchTrueFalseTotal
if $childFinishSub 0 113 113
489 if $childFinishSub;
490 113 return @$retval;
491 }
492  
493 sub printChangesToParent {
494 15 ▶ my ($self, $error, $retval, $parentWtr) = @_;
Subroutine printChangesToParent: called CC=3 SCAR=11.0
Pod undocumented
495 15 my $outputNr = 0;
496 15 my @childInfo = ($error, $retval);
497 15 foreach (@{$$self{tieObjects}}) {
498 30 push @childInfo, $_->getChildInfo();
499 }
500 {
501 15 local $SIG{PIPE} = sub {
502 0 ▶ die "Couldn't print to pipe";
Subroutine __ANON__: not called CC=1 SCAR=6.9
503 15 };
504 15 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'workingSelect'}) { } 10 5 15
505 10 print $parentWtr Storable::freeze(\@childInfo);
506 } else {
507 5 my ($fh, $filename) = tempfile();
508 5 binmode $fh;
509 5 print $fh Storable::freeze(\@childInfo);
510 5 close $fh;
511 5 print $parentWtr $filename;
512 }
513 }
514 }
515  
516 sub while {
517 33 ▶ my ($self, $continueSub, $bodySub, $finishSub) = @_;
Subroutine while: called CC=13 SCAR=25.7
Pod documented
518 33 my @retvals;
519  
520 # This is used if $$self{workingSelect}
521 33 my $childCounter = 0;
522 33 my $nrRunningChildren = 0;
523 33 my $select = IO::Select->new();
524  
525 # Else this is used
526 33 my %childHandles;
527  
528 33 my $fm = Parallel::ForkManager->new($$self{maxProcs});
529 33 $$self{forkManager} = $fm;
530 33 my %childFinishSubs;
531 $fm->run_on_finish( sub {
532 114 ▶ my ($pid) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
533 114 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'workingSelect'}) { } 101 13 114
534 101 $nrRunningChildren--;
535 } else {
536 13 my $childRdr = $childHandles{$pid};
537 push @retvals, $self->readChangesFromChild(
538 13 $childRdr, $childFinishSubs{$childRdr}
539 );
540 13 close $childRdr;
541 }
542 33 });
543 33 ▶ while (my $childData = $continueSub->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $childData = &$continueSub()) 135 18 153
544 # Setup pipes so the child can send info back to the parent about
545 # output data.
546 135 my $parentWtr = IO::Handle->new();
547 135 my $childRdr = IO::Handle->new();
548 135 ▶ pipe( $childRdr, $parentWtr )
Branch: 1 branch
BranchTrueFalseTotal
pipe $childRdr, $parentWtr or die "Couldn't open a pipe" 0 135 135
549 or die "Couldn't open a pipe";
550 135 binmode $parentWtr;
551 135 binmode $childRdr;
552 135 $parentWtr->autoflush(1);
553  
554 135 ▶ if ($finishSub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($finishSub) 0 135 135
555 $childFinishSubs{$childRdr} = sub {
556 0 ▶ $finishSub->($childData);
Subroutine __ANON__: not called CC=1 SCAR=6.9
557 0 };
558 }
559  
560 135 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"workingSelect"}) 115 20 135
561 # Read data from children that are ready. Block if maxProcs has
562 # been reached, so that we are sure to close some file handle(s).
563 my @ready = $select->can_read(
564 115 ▶ $nrRunningChildren >= $$self{maxProcs} ? undef : 0
Branch: 1 branch
BranchTrueFalseTotal
$nrRunningChildren >= $self->{'maxProcs'} ? : 42 73 115
565 );
566 115 for my $fh ( @ready ) {
567 push @retvals, $self->readChangesFromChild(
568 77 $fh, $childFinishSubs{$fh}
569 );
570 77 $select->remove($fh);
571 77 close $fh;
572 }
573 }
574  
575 135 my $pid = $fm->start( ++$childCounter );
576 135 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) 120 15 135
577 # We're running in the parent...
578 120 close $parentWtr;
579 120 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'workingSelect'}) { } 105 15 120
580 105 $nrRunningChildren++;
581 105 $select->add($childRdr);
582 } else {
583 15 $childHandles{$pid} = $childRdr;
584 }
585 120 next;
586 }
587  
588 # We're running in the child
589 15 close $childRdr;
590  
591 15 my @retval;
592 15 eval {
593 15 @retval = $bodySub->();
594 };
595 15 my $error = $@;
596  
597 15 ▶ if (! defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 15 0 15
598 # Lets not waste any energy printing stuff to the parent, if the
599 # parent isn't going to use the return values anyway
600 15 @retval = ();
601 }
602  
603 15 $self->printChangesToParent($error, \@retval, $parentWtr);
604 15 close $parentWtr;
605  
606 15 $fm->finish($childCounter); # pass an exit code to finish
607 }
608  
609 18 ▶ if ($$self{workingSelect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"workingSelect"}) 17 1 18
610 17 ▶ while (my @ready = $select->can_read()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@ready) = $select->can_read) 23 17 40
611 23 for my $fh (@ready) {
612 push @retvals, $self->readChangesFromChild(
613 23 $fh, $childFinishSubs{$fh}
614 );
615 23 $select->remove($fh);
616 23 close $fh;
617 }
618 }
619 }
620  
621 18 $fm->wait_all_children;
622 18 delete $$self{forkManager};
623 18 return @retvals;
624 }
625  
626 # foreach is implemented via while above
627 sub foreach {
628 16 ▶ my ($self, $varRef, $arrayRef, $sub);
Subroutine foreach: called CC=2 SCAR=7.2
Pod documented
629 16 ▶ if (ref $_[1] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[1] eq 'ARRAY') { } 16 0 16
630 16 ($self, $arrayRef, $sub) = @_;
631 } else {
632 # Note that this second usage is not documented (and hence not
633 # supported). It isn't really useful, but this is how to use it just in
634 # case:
635 #
636 # my $foo;
637 # my %returnValues = $pl->foreach( \$foo, [ 0..9 ], sub {
638 # $foo => sqrt($foo);
639 # });
640 0 ($self, $varRef, $arrayRef, $sub) = @_;
641 }
642 16 my $i = -1;
643 81 ▶ $self->while( sub { ++$i <= $#{$arrayRef} }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
644 # Setup either $varRef or $_, if no such given before calling $sub->()
645 5 ▶ if ($varRef) {
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if ($varRef) { } 0 5 5
646 0 $$varRef = $arrayRef->[$i];
647 } else {
648 5 $_ = $arrayRef->[$i];
649 }
650 5 $sub->();
651 16 });
652 }
653  
654 package Parallel::Loops::TiedHash;
655 16 ▶use Tie::Hash;
Subroutine BEGIN: called CC=1 SCAR=0.0
656 16 ▶use base 'Tie::ExtraHash';
Subroutine BEGIN: called CC=1 SCAR=0.0
657  
658 sub TIEHASH {
659 16 ▶ my ( $class, $loops, $storageRef ) = @_;
Subroutine TIEHASH: called CC=1 SCAR=0.0
660 16 my $storage = bless [ {}, { loops => $loops, childKeys => {} } ], $class;
661 16 $$storageRef = $storage;
662 16 return $storage;
663 }
664  
665 sub STORE {
666 128 ▶ my ( $data, $key, $value ) = @_;
Subroutine STORE: called CC=2 SCAR=6.9
667  
668 128 my $hash = $$data[0];
669 128 my $extra = $$data[1];
670 128 my $loops = $$extra{loops};
671  
672 128 ▶ if ( $loops->in_child() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loops->in_child) 15 113 128
673 15 $$extra{childKeys}{$key} = $value;
674 }
675  
676 # warn sprintf "Setting $key to $value";
677 128 $$hash{$key} = $value;
678 }
679  
680 sub getChildInfo {
681 15 ▶ my ($self, $outputNr) = @_;
Subroutine getChildInfo: called CC=1 SCAR=0.0
682 15 my $extra = $$self[1];
683 15 return $extra->{childKeys};
684 }
685  
686 package Parallel::Loops::TiedArray;
687 16 ▶use Tie::Array;
Subroutine BEGIN: called CC=1 SCAR=0.0
688 16 ▶use base 'Tie::Array';
Subroutine BEGIN: called CC=1 SCAR=0.0
689  
690 sub TIEARRAY {
691 16 ▶ my ( $class, $loops, $storageRef ) = @_;
Subroutine TIEARRAY: called CC=1 SCAR=0.0
692 16 my $storage = bless { arr => [], loops => $loops, childArr => [] }, $class;
693 16 $$storageRef = $storage;
694 16 return $storage;
695 }
696  
697 159 ▶sub FETCHSIZE { scalar @{ $_[0]->{arr} } }
Subroutine FETCHSIZE: called CC=1 SCAR=0.0
698 0 ▶sub STORESIZE { $#{ $_[0]->{arr} } = $_[1] - 1 }
Subroutine STORESIZE: not called CC=1 SCAR=6.9
699 90 ▶sub STORE { $_[0]->{arr}->[ $_[1] ] = $_[2] }
Subroutine STORE: called CC=1 SCAR=0.0
700 180 ▶sub FETCH { $_[0]->{arr}->[ $_[1] ] }
Subroutine FETCH: called CC=1 SCAR=0.0
701 51 ▶sub CLEAR { @{ $_[0]->{arr} } = () }
Subroutine CLEAR: called CC=1 SCAR=0.0
702 0 ▶sub POP { pop( @{ $_[0]->{arr} } ) }
Subroutine POP: not called CC=1 SCAR=6.9
703 0 ▶sub SHIFT { shift( @{ $_[0]->{arr} } ) }
Subroutine SHIFT: not called CC=1 SCAR=6.9
704 0 ▶sub UNSHIFT { my $o = shift; unshift( @{ $o->{arr} }, @_ ) }
Subroutine UNSHIFT: not called CC=1 SCAR=6.9
705 0 ▶sub EXISTS { exists $_[0]->{arr}->[ $_[1] ] }
Subroutine EXISTS: not called CC=1 SCAR=6.9
706 0 ▶sub DELETE { delete $_[0]->{arr}->[ $_[1] ] }
Subroutine DELETE: not called CC=1 SCAR=6.9
707  
708 sub PUSH {
709 128 ▶ my $self = shift;
Subroutine PUSH: called CC=2 SCAR=6.9
710  
711 128 ▶ if ( $$self{loops}->in_child() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"loops"}->in_child) 15 113 128
712 15 push( @{ $self->{childArr} }, @_ );
713 }
714  
715 128 push( @{ $self->{arr} }, @_ );
716 }
717  
718 sub getChildInfo {
719 15 ▶ my ($self) = @_;
Subroutine getChildInfo: called CC=1 SCAR=0.0
720 15 return $self->{childArr};
721 }
722  
723 16 1;
↑ Summary createTarball.pl »