如何在不杀死整个程序的情况下立即杀死Perl线程?

时间:2011-08-09 19:00:49

标签: multithreading perl

当我使用exitdie时,它会杀死整个程序。

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

有什么想法吗?

3 个答案:

答案 0 :(得分:7)

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

请参阅perldoc perlthrtut - Ignoring a Thread


perldoc threads解释了代码退出的原因:

threads->exit()
     

如果需要,可以随时通过调用退出一个线程   threads->exit()。这将导致线程在a中返回undef   标量上下文,或列表上下文中的空列表。从来电时    main 线程,其行为与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()会   终止申请。主线程不受此调用的影响。


下面的示例使用了$unwanted线程的signal to terminate

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 :(得分:3)

如果要杀死某个帖子,请使用$thread->kill将其删除。如果您想要断开一个线程但让它保持运行,请使用$thread->detachthreads->exit导致当前线程退出;它不会将线程视为调用者。

答案 2 :(得分:0)

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

相关问题