use threads; use LWP::UserAgent qw( ); my $ua = LWP::UserAgent->new(); my @threads; for my $url ('http://www.google.com/', 'http://www.perl.org/') { push @threads, async { $ua->get($url) }; } for my $thread (@threads) { my $response = $thread->join; ... }
The best part is that the parent does not wait for all requests to complete. Once the correct request is complete, the parent will be unlocked to process it.
If you used Parallel :: ForkManager or something else where you cannot wait for a specific child, you can use the following code to order the results:
for my $id (0..$#urls) { create_task($id, $urls[$id]); } my %responses; for my $id (0..$#urls) { if (!exists($responses{$id})) { my ($id, $response) = wait_for_a_child_to_complete(); $responses{$id} = $response; redo; } my $response = delete($responses{$id}); ... }
source share