#! perl -slw use strict; use Time::HiRes qw[ time ]; use threads; use Thread::Queue; sub worker { my $tid = threads->tid; print "Thread: $tid started"; my $Q = shift; while( my $workitem = $Q->dequeue ) { print "Thread: $tid processing workitem $workitem"; sleep $workitem; } print "Thread: $tid ended"; } our $WORKERS //= 10; our $ITEMS //= 1000; our $MAXWORK //= 2; my $Q = new Thread::Queue; my @workers = map threads->create( \&worker, $Q ), 1 .. $WORKERS; for ( 1 .. $ITEMS ) { sleep 1 while $Q->pending > $WORKERS; $Q->enqueue( rand( $MAXWORK ) ); print "main Q'd workitem $_"; } print "Main: telling threads to die"; $Q->enqueue( (undef) x $WORKERS ); print "Main waiting for threads to die"; $_->join for @workers;