#! perl -slw
use strict;
use threads;
use Thread::Queue;
sub worker {
my $Q = shift;
while( my $workItem = $Q->dequeue ) {
printf "[%d] Processing workiterm '%s'\n", threads->tid, $workItem;
sleep rand( 2 ); ## process $workitem
}
}
our $WORKERS ||= 10;
my $Q = new Thread::Queue;
my @threads = map{ threads->create( \&worker, $Q ) } 1 .. $WORKERS;
while( <> ) { ## Get workitems from stdin
chomp;
$Q->enqueue( $_ ); ## And queue them to the worker pool
}
$Q->enqueue( (undef) x $WORKERS ); ## Signal no more work
$_->join for @threads; ## Wait for tehm to finish;
exit; ## Done
####
> ls * | perl -s tdemo.pl -WORKERS=5
[1] Processing workiterm '2of12inf.dic'
[1] Processing workiterm '2of12inf.txt'
[1] Processing workiterm '3'
[4] Processing workiterm '345241'
...
####
>tdemo -WORKERS=3 work.dat
[2] Processing workiterm '00001'
[1] Processing workiterm '00002'
[2] Processing workiterm '00003'
[1] Processing workiterm '00004'
[2] Processing workiterm '00005'
[1] Processing workiterm '00006'
[3] Processing workiterm '00007'
[2] Processing workiterm '00008'
...