1

我知道我可以使用其他类,但是我想使用 LWP。此处接受的答案(如何在 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, $response) 对存储在一个数组中。我将它们全部推送到异步进程中,并且 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];
}
4

1 回答 1

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 ->
}
于 2013-06-20T14:39:17.003 回答