2011-11-30 24 views
2

我有一个Perl脚本,在验证某个表达式时启动线程。如何在线程完成后清理线程?

while ($launcher == 1) { 
    # do something 
    push @threads, threads ->create(\&proxy, $parameters); 
    push @threads, threads ->create(\&ping, $parameters); 
    push @threads, threads ->create(\&dns, $parameters); 
    # more threads 
    foreach (@threads) { 
    $_->join(); 
    } 
} 

第一循环运行正常,但在第二个脚本与以下错误退出:

Thread already joined at launcher.pl line 290. Perl exited with active threads: 1 running and unjoined 0 finished and unjoined 0 running and detached

我想我应清洁@threads但我怎么能做到这一点?我甚至不确定这是否是问题。

+1

它可能不是你的唯一的问题,但肯定会是一个问题。在循环中第一次加入'@threads [0..2]'。然后尝试加入'@threads [0..5]',其中三个线程已经加入。 – flesk

回答

5

就明确@threads在循环的末尾:

@threads =(); 

或者更好,在循环的开头声明@threadsmy

while ($launcher == 1) { 
    my @threads; 
+0

我想你比我更优雅。尽管你在提到'@ threads'时有一个错字。 – flesk

+0

这实际上工作!我不知道为什么,但我认为这比那大声笑要困难得多,非常感谢! – raz3r

2

最简单的解决方案是在while循环中创建数组(while {my @threads; ...}),除非您在其他地方需要它。否则,您可以在while循环结束时仅使用@threads =()@threads = undef

你也可以设置一个变量my $next_thread; while循环外面,然后分配$next_thread = @threads第一件事就是while循环,改变你的foreach环路

for my $index ($next_thread .. $#threads) { 
    $threads[$index]->join(); 
} 

或跳过这一点,只是循环,在过去的一个切片3个加入线程

for (@threads[-3..-1) { 
    $_->join(); 
} 
相关问题