BBQ has asked for the wisdom of the Perl Monks concerning the following question:

So, I wanted to get some monkly feedback on whether this makes sense or not, whether it seems like a reasonable approach to my problem. This is my first incursion into the beautiful work of threads and everything seems to work as intended but hey, peer review wouldn't hurt.

I wrote a subroutine that uses WWW::Mechanize to simulate user activity on a few pages / web forms. I have an input file with a few thousand records that passes parameters to the said subroutine, but I wanted to have 5 concurrent sessions and no more than 5. After doing a little reading on-line, it seemed like threads was a good candidate for this type of scenario so I wrote the following test script as a proof of concept.

It seems to work well but as they say, there's always more than one way of doing things. Oh, and I'm running ActiveState Perl 5.8.8 (build 822) on Windows XP.

Any takers?
#!/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"; }