BBQ has asked for the wisdom of the Perl Monks concerning the following question:
#!/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) ." thre +ads 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"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Controlling Thread Numbers
by NetWallah (Canon) on Oct 13, 2007 at 01:21 UTC | |
by BBQ (Curate) on Oct 19, 2007 at 02:01 UTC | |
by NetWallah (Canon) on Oct 21, 2007 at 20:44 UTC |