简体   繁体   English

线程中的 perl getstore

[英]perl getstore in thread

In the following script:在以下脚本中:

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();
});

when I launch this it doesn't save the image, but if I launch the same code not in thread it works, why?当我启动它时,它不会保存图像,但是如果我在不在线程中启动相同的代码,它会起作用,为什么?

Because "detach" doesn't do what you'd expect.因为“分离”不会做你所期望的。 Detached threads are terminated when the program exits.分离的线程在程序退出时终止。 From the docs...从文档...

$thr->detach() $thr->分离()

Makes the thread unjoinable, and causes any eventual return value to be discarded.使线程不可连接,并导致丢弃任何最终返回值。 When the program exits, any detached threads that are still running are silently terminated.当程序退出时,任何仍在运行的分离线程都将被静默终止。

You should have gotten a message like this.你应该收到这样的消息。

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

Instead of detaching, you should wait until all threads are complete at the end of your program.您应该等到所有线程在程序结束时完成,而不是分离。

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

If all you want is to make parallel HTTP requests, there's no need for threads.如果您只想发出并行 HTTP 请求,则不需要线程。 LWP::Parallel will probably be more efficient. LWP::Parallel可能会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM