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";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.