0

Im trying to count whenever a thread is done in perl, and print the count. but this is not working. i keep getting either "0" or "1", im trying to add to the count then print the count right after the get request is made.

use strict;
use threads;
use LWP::UserAgent;

our $MAX //= $ARGV[1];

my $list = $ARGV[0];
open my $handle, '<', $list;
chomp(my @array = <$handle>);
close $handle;
my $lines = `cat $list | wc -l`;
my $count = 0;

my @threads;
foreach $_ (@array) {
    push @threads, async{
        my @chars = ("a".."z");
        my $random = join '', map { @chars[rand @chars] } 1 .. 6;

        my $ua = LWP::UserAgent->new;
        my $url = $_ . '?session=' . $random;
        my $response = $ua->get($url);
        count++;
        print $count;
    };
    sleep 1 while threads->list( threads::running ) > $MAX;
}
$_->join for @threads;
AntonH
  • 6,359
  • 2
  • 30
  • 40
jogndogn
  • 13
  • 3

1 Answers1

1

Just to summarise points in comments by @choroba and myself, and not leave the question without an answer.

You would need to include:

use threads::shared;

in your code, along with all the other use elements.

And to indicate that variable $count is shared:

my $count :shared = 0;

EDIT As per Ikegami's comment, you would have to lock the variable if you want to modify it, to avoid problems of concurrency.

{
    lock($count);
    $count++;
    print $count;
}

And that should be enough for the variable $count to be shared.

ikegami
  • 367,544
  • 15
  • 269
  • 518
AntonH
  • 6,359
  • 2
  • 30
  • 40