2013-06-20 21 views
1

我知道还有其他类可以使用,但是我想使用LWP。这里接受的答案(How do I make parallel HTTP requests in Perl, and receive them back in order?)做我想要的,但我需要“标记”线程,以便我可以匹配请求与响应。我已经修改了代码如下:在Perl中为异步HTTP请求线程“标记”

#Setup and query the DB: 

#hold all response\id pairs 
my @response_bundles; 
while (my @row = $query->fetchrow_array()) { 
       my $id = $row[0]; 
       my $url = $row[1]; 

       push @threads, async { 
         my @container_hash; 
         $container_hash[0] = @row; 
         $container_hash[1] = $ua->get($url); 

         push @response_bundles, @container_hash; 
       }; 
}  

#Once this loop terminates all threads are done 
for my $thread (@threads) { 
       $thread->join; 
} 

#Since all threads are completed we can now sort through the response bundles 
for my $response_bundle (@response_bundles) { 
       print "test\n"; 
} 

我的目标是踢一串HTTP请求和存储他们($ ID,$回应)对在数组中。我将它们全部推入异步过程,并且async {}中的子应该这样做(但不是)。我遍历线程数组,一旦完成,所有线程都应该完成。然后我通过我的捆绑和做的事情,但“打印测试”从来没有射击。我在想这个错吗?

编辑:

每我试图返回值的评论,但是这并不工作,要么

while (my @row = $query->fetchrow_array()) { 
       my $id = $row[0]; 
       my $url = $row[1]; 

       push @threads, async { 
         my @container_hash; 
         $container_hash[0] = @row; 
         $container_hash[1] = $ua->get($url); 

         return @container_hash; 
       }; 
}  

#Once this loop terminates all threads are done 
for my $thread (@threads) { 
       my @container; 
       @container = $thread->join; 
       print $container[1]; 
} 
+0

线程运行在不同的解释器中,不共享数据,除非变量明确标记为共享。您可以从线程返回值,并在'$ thread-> join'处收集它们。 – amon

+0

嗨,感谢您的评论。我做了你所说的,但它也不起作用。 –

回答

1

你需要return你从你的线程所需要的数据,这样主程序可以处理它:

while (my @row = $query->fetchrow_array()) { 
       my $id = $row[0]; 
       my $url = $row[1]; 

       push @threads, async { 
         my @container_hash; 
         $container_hash[0] = \@row; #I think you need this 
         $container_hash[1] = $ua->get($url); 

         return \@container_hash; #and here we return reference to our data 
       }; 
}  

#Once this loop terminates all threads are done 
for my $thread (@threads) { 

       my $container = $thread->join; 
       print $container->[1], "\n"; #this is a reference that's why we use -> 
}