2

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?

Nagaraju
  • 1,853
  • 2
  • 27
  • 46
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33

1 Answers1

2

Because "detach" doesn't do what you'd expect. Detached threads are terminated when the program exits. 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.

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. LWP::Parallel will probably be more efficient.

Community
  • 1
  • 1
Schwern
  • 153,029
  • 25
  • 195
  • 336
  • I'd also note - for this sort of model, spawning a new thread per request is a really inefficient way of doing it, and you'd be far better off doing something worker-threads style [something like this](http://stackoverflow.com/questions/26296206/perl-daemonize-with-child-daemons). But `LWP::Parallel` is probably a better choice in this scenario :) – Sobrique Jan 20 '17 at 10:40
  • I appreciate the tips of @Sobrique. The answer of Schwern is correct, thanks!! – Mauro Sala Jan 20 '17 at 11:01