【问题标题】:Thread "tagging" in Perl for async HTTP requestPerl 中用于异步 HTTP 请求的线程“标记”
【发布时间】:2013-06-20 13:17:57
【问题描述】:

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

#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];
}

【问题讨论】:

  • 线程在不同的解释器中运行并且不共享数据,除非变量被明确标记为共享。您可以从线程返回值,并在$thread->join 收集它们。
  • 您好,感谢您的评论。我做了你所说的,但它也不起作用。

标签: multithreading perl http


【解决方案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 ->
}

【讨论】:

    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多