Perl:在退出之前清理活动线程

时间:2015-03-31 02:19:19

标签: multithreading perl

sub handle_sigterm {
    my @running = threads->list(threads::running);
    for my $thr (@running) {
        $thr->kill('SIGTERM')->join();
    }
    threads->exit;
} ## end sub handle_sigterm


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

看起来像handle_sigterm退出而没有清理线程?

我能做些什么来清理线程?

1 个答案:

答案 0 :(得分:3)

threads->exit没有按照您的想法行事。它退出当前线程,而不是所有线程。在线程之外,它就像调用exit

threads->exit()
    If needed, a thread can be exited at any time by calling
    "threads->exit()".  This will cause the thread to return "undef" in
    a scalar context, or the empty list in a list context.

    When called from the main thread, this behaves the same as exit(0).

你想要的是等待所有线程完成......

$_->join for threads->list;

或者要分离所有线程,它们将在程序退出时终止。

$_->detach for threads->list;

此外,您希望使用threads->list来获取所有未加入,未分离的线程的列表,无论是否运行。 threads->list(threads::running)只会为您提供仍在运行的主题。如果任何线程已完成但尚未加入,则将错过。