J
J
jslby2015-07-12 17:46:55
Perl
jslby, 2015-07-12 17:46:55

How to implement threads in Perl?

I want to deal with multithreading on a simpler script:

use strict;
use warnings;
use Getopt::Std;
use HTTP::Cookies;
use threads;
use threads::shared;
use LWP;
use HTTP::Request::Common qw(POST);
use HTTP::Request::Common qw(GET);
use Data::Dumper qw(Dumper);

my $cookie_jar = HTTP::Cookies->new(
    file => 'wpcheck.dat',
    autosave => 1,
);

getopt('d:t:');

our($opt_d, $opt_t, $dfh);

my @threads;
my @domains;
my @running;

open($dfh, '<:encoding(UTF-8)', $opt_d) or die "Could not open '$opt_d' $!";
while(my $thisDomain = <$dfh>){
    chomp $thisDomain;
    push @domains, $thisDomain;
}

while(@domains){
    @running = threads->list(threads::running);
    if(scalar @running < $opt_t){
        push @threads, threads->new(\&check);
        # Вот тут скрипт выходит и всё.
    }
   
    foreach (@threads){
        if($_->is_joinable()){
            $_->join();
        }
    }
}

sub check{
    my $el = pop(@domains);
    my $ua = LWP::UserAgent->new;

    $ua->cookie_jar($cookie_jar);

    my $resp = $ua->get("http://$el/wp-login.php");

    if($resp->code() == 200){
        print "$el\n";
    }
}

Unsubscribed with a comment in the code where the script stops. No errors or warnings. I just can't understand it. The essence of the script:
The script is launched and receives a queue of domains from a file.
Creates a queue of threads equal to the incoming parameter -t
Runs a loop while there are domains in the array and continually adds and starts new threads. The stream processing function removes one domain from the shared array and performs operations on it. Accordingly, the main cycle will end when all domains are over.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rozello, 2015-07-19
@Rozello

Judging by the task, I can say that it probably makes sense for you to look towards the Coro module, otherwise your threads will eat resources like crazy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question