You previously asked this question in a comment to question about collecting the responses in the same order as the requests were placed, and the code you posted was copied from an answer to that question. As such, I presume this is what you want as well.
What follows isn't the most efficient solution since there's no thread reuse, but it makes it easy to collect the responses in the order you desire.
use threads;
use LWP::UserAgent qw( );
my @urls = ...;
my $ua = LWP::UserAgent->new();
my @threads;
for (1..200) {
last if !@urls;
my $url = shift(@urls);
push @threads, async { $ua->get($url) };
}
while (@threads) {
my $thread = shift(@threads);
my $response = $thread->join;
if (@urls) {
my $url = shift(@urls);
push @threads, async { $ua->get($url) };
}
...
}
By using the worker model, you can reuse threads to avoid the time it takes to start them up. This also collects the responses in the order you desire.
use threads;
use Thread::Queue 3.01 qw( );
my $request_q = Thread::Queue->new();
my $response_q = Thread::Queue->new();
my @threads;
push @threads, async {
my $ua = LWP::UserAgent->new();
while (my $url = $request_q->dequeue()) {
$response_q->enqueue([ $url, $ua->get($url) ]);
}
};
$request_q->enqueue($_) for @urls;
$request_q->end();
my %responses;
for my $url (@urls) {
while (!$responses{$url}) {
my ($response_url, $response) = @{ $response_q->dequeue() };
$responses{$response_url} = $response;
}
my $response = delete($responses{$url});
...
}
$_->join for @threads;