【问题标题】:perl getstore in threadperl getstore 在线程中
【发布时间】:2017-06-05 02:43:36
【问题描述】:

在以下脚本中:

use strict;
use warnings;
use LWP::Simple;
use threads;
threads->create(sub { 
    my $url = "http://www.example.com/logo.jpg"; 
    my $file = "/var/www/html/logo.jpg"; 
    getstore($url, $file);
    threads->detach();
});

当我启动它时,它不会保存图像,但如果我在线程中启动相同的代码它会起作用,为什么?

【问题讨论】:

  • 你为什么使用threads
  • 我需要同时为多个 url 运行这个脚本

标签: multithreading perl


【解决方案1】:

因为“分离”没有达到您的预期。当程序退出时,分离的线程被终止。 From the docs...

$thr->分离()

使线程不可连接,并导致任何最终返回值被丢弃。 当程序退出时,任何仍在运行的分离线程都会被静默终止。

你应该收到这样的消息。

Perl exited with active threads:
    1 running and unjoined
    0 finished and unjoined
    0 running and detached

您应该等到程序结束时所有线程都完成,而不是分离。

for my $thread (threads->list(threads::running)) {
    $thread->join;
}

如果您只想发出并行 HTTP 请求,则不需要线程。 LWP::Parallel 可能会更有效率。

【讨论】:

  • 我还要注意 - 对于这种模型,为每个请求生成一个新线程是一种非常低效的方法,你最好做一些工作线程风格的事情@ 987654323@。但是LWP::Parallel 在这种情况下可能是更好的选择:)
  • 我很欣赏@Sobrique 的提示。 Schwern的回答是正确的,谢谢!!
猜你喜欢
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
相关资源
最近更新 更多