2013-02-27 65 views
1

我有一个Perl脚本处理线程,如何在函数成功执行后退出函数而不退出脚本?退出perl函数而不退出脚本

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

我原来的脚本是单块的,没有任何功能,完成后只是“退出”。

这是我创建的线程:

for(0..$threads-1) {$trl[$_] = threads->create(\&mysub, $_);} 
for(@trl) { $_->join; } 

和我分:

sub mysub { 
# do something and if success 
exit; 
} 

编辑

我的完整剧本有问题的:

#!/usr/bin/perl 

use LWP::UserAgent; 
use HTTP::Cookies; 
use threads; 
use threads::shared; 

################################################## ###### 
$|=1; 
my $myscript = '/alive.php'; 
my $h = 'http://'; 
my $good : shared = 0; 
my $bad : shared = 0; 
$threads = 10; 
################################################## ###### 
open (MYLOG , "<myservers.log"); 
chomp (my @site : shared = <MYLOG>); 
close MYLOG; 
################################################## ###### 
$size_site = scalar @site; 
print "Loaded sites: $size_site\n"; 
################################################## ###### 
my $browser = LWP::UserAgent->new; 
$browser -> timeout (10); 
$browser->agent("User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.8;" . $browser->agent); 

################################################## ###### 
for(0..$threads-1) {$trl[$_] = threads->create(\&checkalive, $_);} 
for(@trl) { $_->join; } 
################################################## ###### 
sub checkalive { 

while (@site){ 

{lock(@site);$url = shift @site;} 
$request = $browser->get("$h$url$myscript")->as_string; 
if ($request =~ /Server Alive/){open (GOOD , ">>alive.txt");print GOOD "$h$url$myscript\n"; $good++;} else {$bad++;} 
print "Alive: $good Offline: $bad\r"; 
} 
} 
close GOOD; 
print "Alive: $good Offline: $bad\n"; 
+2

我建议'使用严格的;'和'使用警告:

您可以在脚本结束前添加这样的事情。这些将极大地帮助编写好的代码和捕捉错误。 – 2013-02-27 11:24:18

回答

1

更新:蒂姆德兰格的加入线程的解决方案可能是你想要的。但在某些情况下,以下方法可能会有用。

您可以实施一些等待逻辑,以确保在退出之前一切都已完成。下面是一个简单的例子:

#!usr/bin/perl 
use strict; 
use warnings; 
use threads; 

sub threaded_task { 
    threads->create(sub { sleep 5; print("Thread done\n"); threads->detach() }); 
} 

sub main { 
    #Get a count of the running threads. 
    my $original_running_threads = threads->list(threads::running); 

    threaded_task(); 

    print "Main logic done. Waiting for threads to complete.\n"; 

    #block until the number of running threads is the same as when we started. 
    sleep 1 while (threads->list(threads::running) > $original_running_threads); 

    print "Finished waiting for threads.\n"; 
} 

main(); 

说明:

  1. 获取运行的线程数的计数。
  2. 开始涉及线程的任何任务。
  3. 在退出程序之前,请等到线程数等于原始计数(您启动的所有线程均已停止)。
4

如果您希望在退出之前完成所有线程,则需要在某个时刻加入它们。在每个脚本的顶部`;

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