#!/usr/bin/perl -w use strict; use threads; my $maxThreads = 5; open(LOGGER,'>>logfile') or die(); for my $num (1..50) { print "Starting thread # $num\n"; my $thread = async { &doStuff($num); }; while (threads->list(threads::running) > $maxThreads) { for my $thread (threads->list(threads::all)) { if ($thread->is_joinable()) { print $thread->join(); } } } } print "Waiting for the last ". threads->list(threads::running) ." threads to finish\n"; while (threads->list(threads::all)) { for my $thread (threads->list(threads::joinable)) { print $thread->join(); } } close LOGGER; sleep(1); sub doStuff { my $num = shift; my $secs = int(rand(3)); print LOGGER "Thread # $num is napping for $secs seconds.\n"; sleep $secs; print LOGGER "Thread # $num is awake.\n"; return "This returned from thread # $num\n"; }