Parallel-Iterator-1.00/0000755000076500001200000000000010717037300013553 5ustar andyadminParallel-Iterator-1.00/Build.PL0000644000076500001200000000157710716111232015055 0ustar andyadmin# $Id: Build.PL 2676 2007-10-03 17:38:27Z andy $ use strict; use warnings; use Module::Build; my $build_class = Module::Build->subclass( class => 'inc::MyBuilder', code => <<' SUBCLASS', sub ACTION_testauthor { my $self = shift; $self->test_files('t', 'xt/author'); $self->generic_test( type => 'default' ); } SUBCLASS ); my $builder = $build_class->new( module_name => 'Parallel::Iterator', license => 'perl', dist_author => 'Andy Armstrong ', dist_version_from => 'lib/Parallel/Iterator.pm', requires => { 'Test::More' => 0, 'Storable' => 0, 'IO::Handle' => 0, 'IO::Select' => 0, 'Config' => 0, perl => '5.8.0', }, add_to_cleanup => ['Parallel-Iterator-*'], ); $builder->create_build_script(); Parallel-Iterator-1.00/Changes0000644000076500001200000000225210717037246015060 0ustar andyadminRevision history for Parallel-Iterator 1.00 2007-11-15 Use CORE::exit for mod_perl compatibility. Thanks to Michael Lackhoff for the fix. Switched to n.nn version numbering. 0.8.0 2007-10-15 Only execute END blocks in parent process. Thanks to Aristotle Pagaltzis for the suggestion and patch. 0.7.0 Added batch and adaptive options. Fixed load balancing inequality. 0.6.0 2007-10-04 Fixed MANIFEST 0.5.0 2007-10-04 Made 0 worker option (non-forked) dclone its input data to achieve the same cloning effect that the forked version exhibits. 0.4.0 2007-10-03 Fixed tests on Windows. 0.3.0 2007-10-02 Made job output and result collection run in sync. Formally job output from the master process ran as quickly as possible. This results in better scheduling and eliminates the possibility of blocking with overlarge data (see t/030-block.t). Added support for iterators throwing errors. 0.2.0 2007-09-20 Renamed Parallel-Iterator. Didn't check Parallel-Workers was available. Duh. 0.1.0 2007-09-20 Initial release. Parallel-Iterator-1.00/MANIFEST0000644000076500001200000000063410717037273014720 0ustar andyadminBuild.PL Changes examples/cpan-faces.pl examples/speedy.pl lib/Parallel/Iterator.pm Makefile.PL MANIFEST META.yml README t/000-load.t t/010-basic.t t/020-data.t t/030-block.t t/040-batch.t t/050-nofork-basic.t t/060-nofork-data.t t/070-nofork-block.t t/080-nofork-batch.t t/lib/NoFork.pm xt/author/pod-coverage.t xt/author/pod.t SIGNATURE Public-key signature (added by MakeMaker) Parallel-Iterator-1.00/META.yml0000644000076500001200000000110510717037273015032 0ustar andyadmin--- #YAML:1.0 name: Parallel-Iterator version: 1.00 abstract: Simple parallel execution license: perl generated_by: ExtUtils::MakeMaker version 6.36_01 distribution_type: module requires: Config: 0 IO::Handle: 0 IO::Select: 0 Storable: 0 Test::More: 0 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.2.html version: 1.2 author: - Andy Armstrong Parallel-Iterator-1.00/Makefile.PL0000644000076500001200000000146510716111232015527 0ustar andyadmin# $Id: Makefile.PL 2676 2007-10-03 17:38:27Z andy $ use strict; use warnings; use ExtUtils::MakeMaker; eval 'use ExtUtils::MakeMaker::Coverage'; warn "Optional ExtUtils::MakeMaker::Coverage not available\n" if $@; WriteMakefile( ( MM->can( 'signature_target' ) ? ( SIGN => 1 ) : () ), NAME => 'Parallel::Iterator', AUTHOR => 'Andy Armstrong ', LICENSE => 'perl', VERSION_FROM => 'lib/Parallel/Iterator.pm', ABSTRACT_FROM => 'lib/Parallel/Iterator.pm', PL_FILES => {}, PREREQ_PM => { 'Test::More' => 0, 'Storable' => 0, 'IO::Handle' => 0, 'IO::Select' => 0, 'Config' => 0, }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'Parallel-Iterator-*' }, ); Parallel-Iterator-1.00/README0000644000076500001200000000053710717037074014450 0ustar andyadminParallel-Iterator version 1.00 INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install DEPENDENCIES None. COPYRIGHT AND LICENCE Copyright (C) 2007, Andy Armstrong This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Parallel-Iterator-1.00/SIGNATURE0000644000076500001200000000373710717037300015051 0ustar andyadminThis file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.55. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 291a45ccdeeb6e5693916049ad0e58818608c76b Build.PL SHA1 d972965ab1a2bb85b2656387ad661e07ecdadaaf Changes SHA1 9f01f0aa132d9419f3f965ba736017c0a4d823bf MANIFEST SHA1 b24a4fea1605908956a297f5874382c1ed62bd4b META.yml SHA1 58bb2c01f795f928162d4e4cf47ab0cef86309ae Makefile.PL SHA1 35e488da01fa519da776f81b02839cf1c76e77a7 README SHA1 cb4079bf82f7b3de0c81e66e0b903cf6512f9848 examples/cpan-faces.pl SHA1 b53725fbf5e0f46304b0cdedcddb725005099dc3 examples/speedy.pl SHA1 051cd531dc60fca7cbbaafc63cc638f5cdf2f520 lib/Parallel/Iterator.pm SHA1 de62ee53164059991db28c1f53c497c76369ff61 t/000-load.t SHA1 78abfb030cd81329c41b9e5ae8b0e0c1601f5c63 t/010-basic.t SHA1 cc130884ccfb02e85c131247672902b85b146cba t/020-data.t SHA1 d7c8c21a4ac216f0e3b7897772cf1dcd7134c6cc t/030-block.t SHA1 6e3027c4eb41d8d0a4b330603c458326361df99e t/040-batch.t SHA1 709d855b3940dd4e4f86c201fa8613e48fc6d037 t/050-nofork-basic.t SHA1 b3d757f6c265b90348cfc227a2d32bc668d3e92b t/060-nofork-data.t SHA1 3bef8d0d12874c55a6fd9e03d34a8a07493f7824 t/070-nofork-block.t SHA1 d4d78762e5c5b46b5ede0c25fd058cfc74abd022 t/080-nofork-batch.t SHA1 1f263d567fb65f16d4107e3eb5da0de28eed215f t/lib/NoFork.pm SHA1 bdd09cf1930990e0da69bcd59e551c6b162f24d0 xt/author/pod-coverage.t SHA1 0190346d7072d458c8a10a45c19f86db641dcc48 xt/author/pod.t -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFHPD68woknRJZQnCERAmtVAKCpQ/AfMXo/Wl82ZxXGgOvSopCo2ACbBVqS 9I42TQZ5lTGJV2uiHFK1sns= =8jKO -----END PGP SIGNATURE----- Parallel-Iterator-1.00/examples/0000755000076500001200000000000010717037273015402 5ustar andyadminParallel-Iterator-1.00/examples/cpan-faces.pl0000755000076500001200000001234010716111232017725 0ustar andyadmin#!/usr/bin/perl use strict; use warnings; use HTML::Tiny; use LWP::UserAgent; use File::Spec; use File::Path; use PerlIO::gzip; use YAML qw; use Getopt::Long; use Parallel::Iterator qw( iterate ); $| = 1; use constant MAIL_RC => 'http://cpan.perl.org/authors/01mailrc.txt.gz'; use constant ICON_BASE => 'http://search.cpan.org/gravatar'; use constant AUTHOR => 'http://search.cpan.org/~'; use constant OUTPUT => 'cpan-faces'; use constant STATE => File::Spec->catfile( OUTPUT, 'work.yml' ); use constant SIZE => 80; my $UPDATE = 0; GetOptions( 'update' => \$UPDATE ) or die "cpan-gravatar.pl [--update]\n"; my $ua = LWP::UserAgent->new; mkpath( OUTPUT ); my $icons = -f STATE ? LoadFile( STATE ) : {}; $SIG{INT} = sub { print "Got SIGINT, stopping\n"; exit; }; my $pid = $$; END { if ( $$ == $pid ) { print "Saving ", STATE, "\n"; DumpFile( STATE, $icons ); my $index = File::Spec->catfile( OUTPUT, 'index.html' ); open my $ih, '>', $index or die "Can't write $index ($!)\n"; print $ih build_page( $icons ); close $ih; } } update( $icons, $UPDATE ? sub { my ( $icons, $id ) = @_; return 0; } : sub { my ( $icons, $id ) = @_; return exists $icons->{$id} && $icons->{$id}->{state} eq 'done'; } ); sub update { my ( $icons, $skip_if ) = @_; print "Getting ", MAIL_RC, "\n"; my $authors = get_authors( MAIL_RC ); open my $ah, '<:gzip', $authors or die "Can't read $authors ($!)\n"; my $iter = iterate( { workers => 20 }, sub { my ( $id, undef ) = @_; print "Checking $id\n"; return save_icon( lc( $id ) ); }, sub { while ( defined( my $line = <$ah> ) ) { next unless $line =~ /^alias\s+(\S+)/; return $1; } return; } ); while ( my ( $id, $icon ) = $iter->() ) { $icons->{$id} = $icon; print "Icon saved as ", $icon->{name}, "\n" if $icon && $icon->{name}; } } sub build_page { my $icons = shift; my $h = HTML::Tiny->new; my @pic = (); for my $id ( sort keys %$icons ) { my $icon = $icons->{$id}; if ( my $img = $icon->{name} ) { push @pic, ( $h->div( { class => 'icon' }, $h->a( { href => user_home( $id ) }, $h->img( { src => File::Spec->abs2rel( $img, OUTPUT ), width => SIZE, height => SIZE, alt => $id } ), ), ) ); } } return $h->html( [ $h->head( [ $h->title( 'The Faces of CPAN' ), $h->link( { rel => 'stylesheet', href => 'style.css', type => 'text/css', media => 'screen' } ) ] ), $h->body( [@pic] ) ] ); } sub get_authors { my $url = shift; my $resp = $ua->get( $url ); if ( $resp->is_success ) { my $name = File::Spec->catfile( OUTPUT, '01mailrc.txt.gz' ); open my $ah, '>', $name or die "Can't write $name ($!)\n"; binmode $ah; print $ah $resp->content; close $ah; return $name; } else { die $resp->status_line; } } sub user_home { my $id = shift; return AUTHOR . lc( $id ); } sub save_icon { my $id = shift; my %ext_map = ( jpeg => 'jpg' ); my ( $data, $type ) = eval { get_icon( $id ) }; if ( $@ ) { return { error => $@, state => 'error' }; } # if ( $data && $data ne $default_image && $type =~ m{ ^image/(\S+) }x ) { if ( $data && $type =~ m{ ^image/(\S+) }x ) { my $ext = $ext_map{$1} || $1; my $name = make_name( $id, $ext ); open my $ih, '>', $name or die "Can't write $name ($!)\n"; binmode $ih; print $ih $data; close $ih; return { name => $name, state => 'done' }; } return { state => 'done' }; } sub make_name { my ( $email, $ext ) = @_; my %enc = ( '@' => '-AT-', '.' => '-DOT-' ); $email =~ s/([@.])/$enc{$1}||$1/eg; return File::Spec->catfile( OUTPUT, "$email.$ext" ); } sub get_icon { my $id = shift; $id =~ s{^(((.).).*)$}{$3/$2/$1}; TRY: for my $ext ( qw( jpg png ) ) { my $url = ICON_BASE . '/' . $id . '.' . $ext; my $resp = $ua->get( $url ); if ( $resp->is_success ) { return ( $resp->content, $resp->header( 'Content-Type' ) ); } elsif ( $resp->code == 404 ) { next TRY; } else { die join ' ', $resp->code, $resp->message; } } return; } Parallel-Iterator-1.00/examples/speedy.pl0000644000076500001200000000120710716111232017213 0ustar andyadmin#!/usr/bin/perl use strict; use warnings; use Inline 'C'; use Parallel::Iterator qw( iterate_as_array ); # Demonstrates a simple way to run multiple instances of a C function in # parallel. You'll need it to be a fairly time consuming function # otherwise the overhead of forking and marshalling arguments will # overwhelm the execution time. my @ar = qw( This Pork Bubble ); @ar = ( @ar, @ar ) for 1 .. 5; my @got = iterate_as_array( sub { calc( $_[1] ) }, \@ar ); print join( ', ', @got ), "\n"; __END__ __C__ int calc(char *str) { int sum = 0; int c; while (c = *str++) { sum = sum << 3 | c; } return sum; } Parallel-Iterator-1.00/lib/0000755000076500001200000000000010717037273014332 5ustar andyadminParallel-Iterator-1.00/lib/Parallel/0000755000076500001200000000000010717037273016066 5ustar andyadminParallel-Iterator-1.00/lib/Parallel/Iterator.pm0000644000076500001200000005306710717037100020215 0ustar andyadmin# $Id: Iterator.pm 2746 2007-10-19 16:36:50Z andy $ package Parallel::Iterator; use warnings; use strict; use Carp; use Storable qw( store_fd fd_retrieve dclone ); use IO::Handle; use IO::Select; use Config; require 5.008; our $VERSION = '1.00'; use base qw( Exporter ); our @EXPORT_OK = qw( iterate iterate_as_array iterate_as_hash ); use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ ); my %DEFAULTS = ( workers => ( ( $Config{d_fork} && !IS_WIN32 ) ? 10 : 0 ), onerror => 'die', nowarn => 0, batch => 1, adaptive => 0, ); =head1 NAME Parallel::Iterator - Simple parallel execution =head1 VERSION This document describes Parallel::Iterator version 1.00 =head1 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; } =head1 DESCRIPTION The 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 CPU systems. There is, however, a considerable overhead associated with forking, so the example in the synopsis (doubling a list of numbers) is I a sensible use of this module. =head2 Example 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 $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 I 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. =head2 Simpler interfaces Having to construct an iterator is a pain so 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 ); =head2 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. =head2 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. =head3 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 C<%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 C<%tally> rather than the copy for the parent process. That means that after the job terminates the C<%tally> in the parent process will be empty. In general you should avoid side effects in your worker subroutines. =head3 Serialization Values are serialised using L 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 L for other caveats. =head3 Performance Process forking is expensive. Only use Parallel::Iterator in cases where: =over =item the worker waits for I/O 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. =item 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. =back =head1 INTERFACE =head2 C<< 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 C will convert it internally into a suitable iterator. If you are doing this you may wish to investigate C and C. =head3 Options A reference to a hash of options may be supplied as the first argument. The following options are supported: =over =item C 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. =item C Normally 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. =item C 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. =item C 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 to heuristically determine the batch size by setting the C option to a numeric value. The batch size will be computed as / / A larger value for 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 ); =item C 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 C<$@> thrown. iterate( { onerror => sub { my ($id, $err) = @_; $self->log( "Error for index $id: $err" ); }, $worker, \@jobs ); The default is 'die'. =back =cut sub _massage_iterator { my $iter = shift; if ( 'ARRAY' eq ref $iter ) { my @ar = @$iter; my $pos = 0; return sub { return if $pos >= @ar; my @r = ( $pos, $ar[$pos] ); $pos++; return @r; }; } elsif ( 'HASH' eq ref $iter ) { my %h = %$iter; my @k = keys %h; return sub { return unless @k; my $k = shift @k; return ( $k, $h{$k} ); }; } elsif ( 'CODE' eq ref $iter ) { return $iter; } else { croak "Iterator must be a code, array or hash ref"; } } sub _nonfork { my ( $options, $worker, $iter ) = @_; return sub { while ( 1 ) { if ( my @next = $iter->() ) { my ( $id, $work ) = @next; # dclone so that we have the same semantics as the # forked version. $work = dclone $work if defined $work && ref $work; my $result = eval { $worker->( $id, $work ) }; if ( my $err = $@ ) { $options->{onerror}->( $id, $err ); } else { return ( $id, $result ); } } else { return; } } }; } # Does this sub look a bit long to you? :) sub _fork { my ( $options, $worker, $iter ) = @_; my @workers = (); my @result_queue = (); my $select = IO::Select->new; my $rotate = 0; return sub { LOOP: { # Make new workers while ( @workers < $options->{workers} && ( my @next = $iter->() ) ) { my ( $my_rdr, $my_wtr, $child_rdr, $child_wtr ) = map IO::Handle->new, 1 .. 4; pipe $child_rdr, $my_wtr or croak "Can't open write pipe ($!)\n"; pipe $my_rdr, $child_wtr or croak "Can't open read pipe ($!)\n"; if ( my $pid = fork ) { # Parent close $_ for $child_rdr, $child_wtr; push @workers, $pid; $select->add( [ $my_rdr, $my_wtr, 0 ] ); _put_obj( \@next, $my_wtr ); } else { # Child close $_ for $my_rdr, $my_wtr; # Don't execute any END blocks use POSIX '_exit'; eval q{END { _exit 0 }}; # Worker loop while ( defined( my $job = _get_obj( $child_rdr ) ) ) { my $result = eval { $worker->( @$job ) }; my $err = $@; _put_obj( [ $err ? ( 'E', $job->[0], $err ) : ( 'R', $job->[0], $result ) ], $child_wtr ); } # End of stream _put_obj( undef, $child_wtr ); close $_ for $child_rdr, $child_wtr; # We use CORE::exit for MP compatibility CORE::exit; } } return @{ shift @result_queue } if @result_queue; if ( $select->count ) { eval { my @rdr = $select->can_read; # Anybody got completed work? for my $r ( @rdr ) { my ( $rh, $wh, $eof ) = @$r; if ( defined( my $results = _get_obj( $rh ) ) ) { my $type = shift @$results; if ( $type eq 'R' ) { push @result_queue, $results; } elsif ( $type eq 'E' ) { $options->{onerror}->( @$results ); } else { die "Bad result type: $type"; } # We operate a strict one in, one out policy # - which avoids deadlocks. Having received # the previous result send a new work value. unless ( $eof ) { if ( my @next = $iter->() ) { _put_obj( \@next, $wh ); } else { _put_obj( undef, $wh ); close $wh; @{$r}[ 1, 2 ] = ( undef, 1 ); } } } else { $select->remove( $r ); close $rh; } } }; if ( my $err = $@ ) { # Finish all the workers _put_obj( undef, $_->[1] ) for $select->handles; # And wait for them to exit waitpid( $_, 0 ) for @workers; # Rethrow die $err; } redo LOOP; } waitpid( $_, 0 ) for @workers; return; } }; } sub _batch_input_iter { my ( $code, $options ) = @_; if ( my $adapt = $options->{adaptive} ) { my $workers = $options->{workers} || 1; my $count = 0; $adapt = [ 1, $adapt, undef ] unless 'ARRAY' eq ref $adapt; my ( $min, $ratio, $max ) = @$adapt; $min = 1 unless defined $min && $min > 1; return sub { my @chunk = (); # Adapt batch size my $batch = $count / $workers / $ratio; $batch = $min if $batch < $min; $batch = $max if defined $max && $batch > $max; while ( @chunk < $batch && ( my @next = $code->() ) ) { push @chunk, \@next; $count++; } return @chunk ? ( 0, \@chunk ) : (); }; } else { my $batch = $options->{batch}; return sub { my @chunk = (); while ( @chunk < $batch && ( my @next = $code->() ) ) { push @chunk, \@next; } return @chunk ? ( 0, \@chunk ) : (); }; } } sub _batch_output_iter { my $code = shift; my @queue = (); return sub { unless ( @queue ) { if ( my ( undef, $chunk ) = $code->() ) { @queue = @$chunk; } else { return; } } return @{ shift @queue }; }; return $code; } sub _batch_worker { my $code = shift; return sub { my ( undef, $chunk ) = @_; for my $item ( @$chunk ) { $item->[1] = $code->( @$item ); } return $chunk; }; } sub iterate { my %options = ( %DEFAULTS, %{ 'HASH' eq ref $_[0] ? shift : {} } ); croak "iterate takes 2 or 3 args" unless @_ == 2; my @bad_opt = grep { !exists $DEFAULTS{$_} } keys %options; croak "Unknown option(s): ", join( ', ', sort @bad_opt ), "\n" if @bad_opt; my $worker = shift; croak "Worker must be a coderef" unless 'CODE' eq ref $worker; my $iter = _massage_iterator( shift ); if ( $options{onerror} =~ /^(die|warn)$/ ) { $options{onerror} = eval "sub { shift; $1 shift }"; } croak "onerror option must be 'die', 'warn' or a code reference" unless 'CODE' eq ref $options{onerror}; if ( $options{workers} > 0 && $DEFAULTS{workers} == 0 ) { warn "Fork not available; falling back to single process mode\n" unless $options{nowarn}; $options{workers} = 0; } my $factory = $options{workers} == 0 ? \&_nonfork : \&_fork; if ( $options{batch} > 1 || $options{adaptive} ) { return _batch_output_iter( $factory->( \%options, _batch_worker( $worker ), _batch_input_iter( $iter, \%options ) ) ); } else { # OK. Ready. Let's do it. return $factory->( \%options, $worker, $iter ); } } =head2 C<< iterate_as_array >> As 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 ); =cut sub iterate_as_array { my $iter = iterate( @_ ); my @out = (); while ( my ( $index, $value ) = $iter->() ) { $out[$index] = $value; } return wantarray ? @out : \@out; } =head2 C<< iterate_as_hash >> As 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 ); =cut sub iterate_as_hash { my $iter = iterate( @_ ); my %out = (); while ( my ( $key, $value ) = $iter->() ) { $out{$key} = $value; } return wantarray ? %out : \%out; } sub _get_obj { my $fd = shift; my $r = fd_retrieve $fd; return $r->[0]; } sub _put_obj { my ( $obj, $fd ) = @_; store_fd [$obj], $fd; $fd->flush; } 1; __END__ =head1 CONFIGURATION AND ENVIRONMENT Parallel::Iterator requires no configuration files or environment variables. =head1 DEPENDENCIES None. =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to C, or through the web interface at L. =head1 AUTHOR Andy Armstrong C<< >> =head1 THANKS Aristotle Pagaltzis for the END handling suggestion and patch. =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Andy Armstrong 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 L. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Parallel-Iterator-1.00/t/0000755000076500001200000000000010717037273014027 5ustar andyadminParallel-Iterator-1.00/t/000-load.t0000644000076500001200000000030110716111231015404 0ustar andyadmin# $Id: 000-load.t 2676 2007-10-03 17:38:27Z andy $ use Test::More tests => 1; BEGIN { use_ok( 'Parallel::Iterator' ); } diag( "Testing Parallel::Iterator $Parallel::Iterator::VERSION" ); Parallel-Iterator-1.00/t/010-basic.t0000644000076500001200000001054110716111231015556 0ustar andyadmin# $Id: 010-basic.t 2701 2007-10-04 20:31:37Z andy $ use strict; use warnings; use Test::More tests => 13; use Parallel::Iterator qw( iterate iterate_as_array iterate_as_hash ); sub array_iter { my @ar = @_; my $pos = 0; return sub { return if $pos >= @ar; my @r = ( $pos, $ar[$pos] ); $pos++; return @r; }; } sub fill_array_from_iter { my $iter = shift; my @ar = (); while ( my ( $pos, $value ) = $iter->() ) { # die "Value for $pos is undef!\n" unless defined $value; $ar[$pos] = $value; } return @ar; } { my @ar = ( 1 .. 5 ); my $iter = array_iter( @ar ); my @got = fill_array_from_iter( $iter ); is_deeply \@got, \@ar, 'iterators'; } for my $workers ( 0, 1, 2, 10 ) { my @nums = ( 1 .. 100 ); my @double = map $_ * 2, @nums; my $done = 0; my $double_iter = iterate( { workers => $workers, nowarn => 1 }, sub { my ( $id, $job ) = @_; return $job * 2; }, array_iter( @nums ) ); my @got = fill_array_from_iter( $double_iter ); is_deeply \@got, \@double, "double, $workers workers"; } # Array iterator { my @input = ( 1 .. 5 ); my @quad = map $_ * 4, @input; my $quad_iter = iterate( { workers => 1, nowarn => 1 }, sub { my ( $id, $job ) = @_; return $job * 4; }, \@input ); my @got = fill_array_from_iter( $quad_iter ); is_deeply \@got, \@quad, "array iterator"; } # iterate_as_array { my @input = ( 1 .. 5 ); my @quad = map $_ * 4, @input; my @got = iterate_as_array( { workers => 1, nowarn => 1 }, sub { my ( $id, $job ) = @_; return $job * 4; }, \@input ); is_deeply \@got, \@quad, "array iterator"; } # Hash iterator { my %input = ( one => 1, three => 3, five => 5, seven => 7, nine => 9 ); my $treble_iter = iterate( { workers => 1, nowarn => 1 }, sub { my ( $key, $job ) = @_; return $job * 3; }, \%input ); my %expect = %input; $_ *= 3 for values %expect; my %output; while ( my ( $k, $v ) = $treble_iter->() ) { $output{$k} = $v; } is_deeply \%output, \%expect, "iterate_as_array"; } # iterate_as_hash { my %input = ( one => 1, three => 3, five => 5, seven => 7, nine => 9 ); my %output = iterate_as_hash( { workers => 1, nowarn => 1 }, sub { my ( $key, $job ) = @_; return $job * 3; }, \%input ); my %expect = %input; $_ *= 3 for values %expect; is_deeply \%output, \%expect, "iterate_as_hash"; } # Empty input { my @input = (); my @got = iterate_as_array( { workers => 1, nowarn => 1 }, sub { my ( $id, $job ) = @_; return $job * 5; }, \@input ); is_deeply \@got, \@input, "array iterator"; } # Die { my @input = ( 1 .. 5 ); my $iter = iterate( { workers => 1, nowarn => 1 }, sub { my ( $id, $job ) = @_; die "Oops"; }, \@input ); eval { $iter->() }; like $@, qr{Oops}, "died OK"; } # Warn { my @input = ( 1 .. 5 ); my $iter = iterate( { workers => 1, onerror => 'warn', nowarn => 1 }, sub { my ( $id, $job ) = @_; die "Oops"; }, \@input ); my @warning; local $SIG{__WARN__} = sub { push @warning, @_; }; $iter->(); like $warning[0], qr{Oops}, "warned OK"; } # Callback { my @input = ( 1 .. 5 ); my @warning; my $iter = iterate( { workers => 1, onerror => sub { push @warning, @_ }, nowarn => 1 }, sub { my ( $id, $job ) = @_; die "Oops"; }, \@input ); $iter->(); like $warning[1], qr{Oops}, "warned OK"; } 1; Parallel-Iterator-1.00/t/020-data.t0000644000076500001200000000176310716111231015415 0ustar andyadmin# $Id: 020-data.t 2683 2007-10-04 12:35:06Z andy $ use strict; use warnings; use Test::More tests => 1; use Parallel::Iterator qw( iterate_as_array ); { my @input = ( { type => 'hash', value => 2 }, [ 1, 2, 3 ], "Hello" ); my @want = ( { type => 'hash', value => 10 }, [ 4, 5, 6, 7, 8, 9 ], "HelloHello" ); my @got = iterate_as_array( { workers => 1, nowarn => 1 }, sub { my ( $id, $job ) = @_; if ( ref $job ) { if ( 'HASH' eq ref $job ) { $job->{value} *= 5; return $job; } elsif ( 'ARRAY' eq ref $job ) { return [ 4, 5, 6, 7, 8, 9 ]; } } else { return $job . $job; } }, \@input ); is_deeply \@got, \@want, "data structure"; } 1; Parallel-Iterator-1.00/t/030-block.t0000644000076500001200000000437310716111231015577 0ustar andyadmin# $Id: 030-block.t 2683 2007-10-04 12:35:06Z andy $ use strict; use warnings; use IO::Handle; use POSIX qw(:errno_h); use Test::More; use Parallel::Iterator qw( iterate_as_array ); my $buffer_size = get_pipe_buffer_size(); plan 'skip_all' => "Can't calculate buffer size" unless defined $buffer_size; plan tests => 1; # diag "I/O buffer size: $buffer_size\n"; { # Random data my $data = join '', map chr rand 256, ( 1 .. $buffer_size * 2 ); # Just in case someone decides to generate data by some other # means... die "Not enough data!" unless length $data > $buffer_size; my @input = ( { type => 'hash', value => $data, }, [ 1, $data, 3 ], $data, ); my @want = ( { type => 'hash', value => "$data!", }, [ $data, $data ], $data . $data, ); for ( 1 .. 4 ) { @input = ( @input, @input ); @want = ( @want, @want ); } my @got = iterate_as_array( { workers => 5, nowarn => 1 }, sub { my ( $id, $job ) = @_; # Just munge the data in a predictable, detectable way... if ( ref $job ) { if ( 'HASH' eq ref $job ) { $job->{value} .= '!'; return $job; } elsif ( 'ARRAY' eq ref $job ) { return [ $data, $data ]; } } else { return $job . $job; } }, \@input ); is_deeply \@got, \@want, "big data structure"; } # Find out how much data we can write to a pipe... sub get_pipe_buffer_size { my ( $in, $out ) = map IO::Handle->new, 1 .. 2; unless ( pipe $in, $out ) { diag "Can't make pipe ($!)\n"; return; } unless ( defined $out->blocking( 0 ) ) { diag "Can't turn off blocking ($!)\n"; return; } my $chunk = ' ' x ( 1024 * 4 ); my $wrote = 0; CHUNK: while ( 1 ) { my $rc = $out->syswrite( $chunk, length $chunk ); last CHUNK if !defined $rc && $! == EAGAIN; $wrote += $rc; last CHUNK if $rc != length $chunk; } close $_ for $in, $out; return $wrote; } 1;Parallel-Iterator-1.00/t/040-batch.t0000644000076500001200000000114310716111231015557 0ustar andyadmin# $Id: 040-batch.t 2696 2007-10-04 18:17:24Z andy $ use strict; use warnings; use Test::More; use Parallel::Iterator qw( iterate_as_array ); my @spec = ( { batch => 97 }, { batch => 100 }, { adaptive => 1 }, { adaptive => 2 }, { adaptive => [ 10, 1, 20 ] } ); plan tests => @spec * 1; for my $spec ( @spec ) { my @in = ( 1 .. 5000 ); my @want = map { $_ * 2 } @in; my @got = iterate_as_array( $spec, sub { my ( $id, $job ) = @_; return $job * 2; }, \@in ); is_deeply \@got, \@want, "processed OK"; } 1; Parallel-Iterator-1.00/t/050-nofork-basic.t0000644000076500001200000000017510716111231017060 0ustar andyadmin# $Id: 050-nofork-basic.t 2700 2007-10-04 20:04:07Z andy $ use strict; use lib 't/lib'; use NoFork; require 't/020-data.t'; Parallel-Iterator-1.00/t/060-nofork-data.t0000644000076500001200000000017410716111231016710 0ustar andyadmin# $Id: 060-nofork-data.t 2700 2007-10-04 20:04:07Z andy $ use strict; use lib 't/lib'; use NoFork; require 't/020-data.t'; Parallel-Iterator-1.00/t/070-nofork-block.t0000644000076500001200000000017610716111231017074 0ustar andyadmin# $Id: 070-nofork-block.t 2700 2007-10-04 20:04:07Z andy $ use strict; use lib 't/lib'; use NoFork; require 't/030-block.t'; Parallel-Iterator-1.00/t/080-nofork-batch.t0000644000076500001200000000017610716111231017064 0ustar andyadmin# $Id: 080-nofork-batch.t 2700 2007-10-04 20:04:07Z andy $ use strict; use lib 't/lib'; use NoFork; require 't/040-batch.t'; Parallel-Iterator-1.00/t/lib/0000755000076500001200000000000010717037273014575 5ustar andyadminParallel-Iterator-1.00/t/lib/NoFork.pm0000644000076500001200000000067110716111231016317 0ustar andyadmin# $Id: NoFork.pm 2683 2007-10-04 12:35:06Z andy $ package NoFork; # This code originally written by Eric Wilhelm for the Test::Harness # project. Thanks Eric - it's just what I needed :) BEGIN { *CORE::GLOBAL::fork = sub { die "you should not fork" }; } use Config; tied( %Config )->{d_fork} = 0; # blatant lie =begin TEST Assuming not too much chdir: PERL5OPT='-It/lib -MNoFork' perl -Ilib bin/prove -r t =end TEST =cut 1; Parallel-Iterator-1.00/xt/0000755000076500001200000000000010717037273014217 5ustar andyadminParallel-Iterator-1.00/xt/author/0000755000076500001200000000000010717037273015521 5ustar andyadminParallel-Iterator-1.00/xt/author/pod-coverage.t0000644000076500001200000000036410716111231020246 0ustar andyadmin#!perl -T use Test::More; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; all_pod_coverage_ok( { private => [ qr{^BUILD|DEMOLISH|AUTOMETHOD|START$}, qr{^_} ] } ); Parallel-Iterator-1.00/xt/author/pod.t0000644000076500001200000000021410716111231016447 0ustar andyadmin#!perl -T use Test::More; eval "use Test::Pod 1.14"; plan skip_all => "Test::Pod 1.14 required for testing POD" if $@; all_pod_files_ok();