LanceDeeply's scratchpad
use strict;
use warnings;
use Data::Dumper;
use threads;
my $slow_matches_b = sub { sleep 1;
return unless $_[0];
return 1 if $_[0] =~ /b/;
};
my $test_strings = [ ('blee','blah','bloo', 'qoo', 'fwee' ) ];
parallel_map($slow_matches_b,$test_strings);
sub serial_map
{
my $function = shift;
my $data = shift;
my @results = map { $slow_matches_b->($_) } @$test_strings;
print Dumper \@results;
}
sub parallel_map
{
my $function = shift;
my $data = shift;
#
# assign keys to each data element
#
my %hash_input;
for ( 0..( @$data-1) )
{
$hash_input{$_} = $$data[$_];
}
#
# run each data element in separate thread
#
my @threads;
for ( keys %hash_input )
{
my $t = threads->create( sub { map_element($_, $function, $has
+h_input{$_} ) } );
push @threads, $t;
}
#
# wait for threads to return ( this implementation is bound by
+slowest thread )
#
my %results = map { %{$_->join()}; } @threads;
print Dumper \%results;
}
sub map_element
{
my $key = shift;
my $function = shift;
my $data = shift;
return { $key => $function->($data) };
}
|