threads->create( \&JobAdder, $q, $maxJobs, [ 0 .. 99 ] );
####
AddJob( $q, shift @$inputs );
####
$q->enqueue( [@_] );
####
while( defined( my $argRef = $q->dequeue ) ) {
####
$callBack->( @$argRef );
####
sub GetFibby {
my( $chunkId ) = @_;
use autodie qw/ open close /;
open my( $outfh ), '>', "fibojob-$chunkId.txt";
####
$q->enqueue( 0 .. 99 );
####
#! perl -slw
use strict;
use threads;
use threads::Q;
sub fibonacci {
my $n = shift;
return undef if $n < 0;
my $f;
if( $n == 0 ) {
$f = 0;
} elsif( $n == 1 ) {
$f = 1;
} else {
$f = fibonacci( $n - 1 ) + fibonacci( $n - 2 );
}
return $f;
}
sub worker {
my $tid = threads->tid;
my( $Q, $path ) = @_;
chdir $path or die "$path : $!";
while( defined( my $chunkId = $Q->dq ) ) {
open my $out, '>', "fibojob-$chunkId.txt" or die "$chunkId : $!";
print $out join "\t", map fibonacci( $_ ), 1 .. 10;
close $out;
}
}
our $T //= 8;
our $P //= '.';
our $M //= 99;
## The pattern is simple
my $Q = threads::Q->new( $T*2 ); ## Create a queue.
my @threads = map threads->create( \&worker, $Q, $P ), 1 .. $T; ## Create some workers to read from that queue.
$Q->nq( 0 .. $M ); ## Queue some work.
$Q->nq( ( undef ) x $T ); ## Tell the workers they are done.
$_->join for @threads; ## And wait for them to finish.