views:

64

answers:

1

I'm writing a multithreaded website uptime checker in perl, and here is the basic code so far (includes only threading part):

#!/usr/bin/perl

use LWP::UserAgent; 
use Getopt::Std; 
use threads; 
use threads::shared; 

my $maxthreads :shared = 50;
my $threads :shared = 0;

print "Website Uptime Checker\n";
my $infilename = $ARGV[0];
chomp($infilename);
open(INFILE, $infilename);
my $outfilename = $ARGV[1];
chomp($outfilename);
open(OUTFILE, ">" . $outfilename);
OUTFILE->autoflush(1);
while ($site = <INFILE>)
{
    chomp($site);
    while (1)
    {
        if ($threads < $maxthreads)
        {
            $threads++;
            my $thr = threads->create(\&check_site, $site);
            $thr->detach();
            last;
        }
        else
        {
            sleep(1);
        }
    }
}
while ($threads > 0)
{
    sleep(1);
}

sub check_site
{
    $server = $_[0];
    print "$server\n";
    $threads--;
}

It gives an error after a while:

Can't call method "detach" on an undefined value at C:\perl\webchecker.pl line 28, line 245.

What causes this error? I know it is at detach, but what am I doing wrong in my code? Windows shows lots of free memory, so it should not be the computer running out of memory, this error occurs even if I set $maxthreads as low as 10 or possibly even lower.

+1  A: 

The specific issue is that thread->create is failing to create a thread and so it is returning undef. You should check the value of thr before calling detach if you want your code to be more robust.

R Samuel Klatchko
ok thanks that seems to work, I added check if undef and if so sleep(1) and try again until it works and it is going through the list just fine now
Alice Wozownik
sorry, an error did occur later on:panic: attempt to copy freed scalar 32c0bb4 to 23b080c at C:\perl\webchecker.pl line 24, <INFILE> line 15863.Attempt to free unreferenced scalar: SV 0x32c0bb4, Perl interpreter: 0x3354584.What caused this error?
Alice Wozownik
Alice Wozownik, it's probably better to [open a new question](http://stackoverflow.com/questions/ask) for this different problem. Paste your code again and also name the version of Perl and of the used `threads` modules.
daxim
Yes, that's a different problem now.
Ether