#! perl -slw use strict; use threads; use Thread::Queue; $| = 1; our $KIDS ||= 10; our $WORK ||= 1000; our $SLEEP||= 10; sub kid { my( $Q ) = shift; my $tid = threads->tid; printf "Kid: %d started\n", $tid; ## Pick a work item off the queue and process it while( my $work = $Q->dequeue ) { printf "Kid: %d processing work item '%s'\n", $tid, $work; ## Replace the sleep with the code to process the work items sleep rand( $SLEEP ); } printf "kid: %d ending\n", $tid; } ## A queue for communications my $Q = new Thread::Queue; ## Start the kids my @kids = map{ threads->create( \&kid, $Q ) } 1 .. $KIDS; ## Wait till they're all up and running sleep 1 until @{[ threads->list ]} == $KIDS; ## Feed the queue with work ## The limit just ensures we don't fill lots of memory for my $workitem ( 1 .. $WORK ) { sleep 1 while $Q->pending > $KIDS *2; print "Queueing work item $workitem"; $Q->enqueue( $workitem ); } ## Tell them to stop $Q->enqueue( (undef) x $KIDS ); ## And wait for them to do so. $_->join for @kids;