multithreading - 线程中的 Perl getstore

标签 multithreading perl

在以下脚本中:

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

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

最佳答案

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

$thr->detach()

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.

您应该收到这样的消息。

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可能会更有效率。

关于multithreading - 线程中的 Perl getstore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758080/

相关文章:

c# - 在哪里停止使用 async/await 关键字?

java - 多线程安全的 JDBC 保存或更新

Java - 使用执行器服务的线程

perl - perl中可以实现Paros代理功能的最佳模块是什么

windows - 如何获得在 Windows 上构建 Perl 模块的工具?

php - 如何从 Linux 上的日志文件中提取 XML block

c - 为什么线程1重复获取锁,线程2就无法获取锁?

java - vfs2 DefaultFileMonitor 线程提前终止

Perl IPC::运行,在父进程死亡时终止进程

perl - 你应该对常量进行测试吗?