2011-08-09 92 views
4

当我使用exitdie时,它会杀死整个程序。如何在不杀死整个程序的情况下立即杀死Perl线程?

foreach my $t (threads->list()) 
{ 
    $t->exit; 
    $count++; 
} 

Usage: threads->exit(status) at main.pl line 265 
Perl exited with active threads: 
     9 running and unjoined 
     0 finished and unjoined 
     0 running and detached 

任何想法?

+0

看到我的评论在这里:https://stackoverflow.com/questions/13708864/how-do-i-kill-perl-threads/27690901#27690901 –

回答

7

要忽略正在执行的线程,返回控制并丢弃任何可能输出的内容,正确的使用方法是detach,而不是exit

参见perldoc perlthrtut - Ignoring a Thread


perldoc threads解释了为什么代码退出:

threads->exit() 

如果需要的话,一个线程可以在任何时候通过调用 threads->exit()退出。这将导致线程在标量上下文中返回undef,或者在列表上下文中返回空列表。当从 主要线程调用时,此行为与exit(0)相同。


有可能的方式来实现instant termination(没有为我工作在Windows上):

use threads 'exit' => 'threads_only'; 

这个全球覆盖调用exit() 一个线程中的默认行为,并且有效地导致此类呼叫的行为与threads->exit()的行为相同 。换句话说,通过这个设置,调用 exit()只会导致线程终止。由于其全局效果 ,此设置不应在模块内部使用。 主线程不受此设置的影响。

的文件也提出另一种方式,使用set_thread_exit_only方法(同样,没有为我工作在Windows上):

$thr->set_thread_exit_only(boolean) 

这可以用来改变出口线程唯一行为对于创建后的线程 。有了真实的参数,exit()将导致 只有线程退出。如果有错误的参数,exit()将会终止该应用程序 。主线程不受此调用的影响。


下面的例子使用了一个杀signal to terminate$unwanted螺纹:

use strict; 
use warnings; 
use threads; 

my $unwanted = threads->create(sub { 
             local $SIG{KILL} = sub { threads->exit }; 
             sleep 5; 
             print "Don't print me!\n"; 
            }); 

my $valid = threads->create(sub { 
             sleep 2; 
             print "This will print!\n"; 
            }); 

$unwanted->kill('KILL')->detach; # Kills $thr, cleans up 

$valid->join;     # sleep 2, 'This will print!' 
+1

不可能完全杀死线程吗?让它走到再见,停止使用我的CPU和RAM? – Saustin

+0

是的,通过'detach'。一旦线程结束,Perl将执行必要的清理。 – 2011-08-09 19:15:52

+1

我想立即停止线程。我应该使用外部方法(全局布尔值来告诉何时停止)吗?我认为这可能有效。 – Saustin

0

错误消息告诉你$t->exit需要参数。尝试给它一个。 (perldoc Threads似乎说它不,但我不知道你使用什么包。)

+0

我正在使用线程。我已经尝试过;没有游戏。我也是这样做的。 – Saustin

+0

'$ t'是线程对象吗?尝试打印'ref $ t'。 “foreach'循环中的表达式真的是'threads-> list()',还是'Threads-> list()'? –

+0

这绝对不是问题。 – Saustin

3

如果你想杀死一个线程,你$thread->kill杀死它。如果您想要断开某个线程但保持运行状态,请使用$thread->detachthreads->exit导致当前线程退出;它不需要一个线程作为invocant。