ealeon
ealeon

Reputation: 12460

Perl: clean up active threads before exiting

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

it looks like handle_sigterm exited without cleaning up the thread?

What can i do clean up the threads?

Upvotes: 0

Views: 620

Answers (1)

Schwern
Schwern

Reputation: 165606

threads->exit doesn't do what you think it does. It exits the current thread, not all threads. Outside of a thread, it's just like calling 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).

What you want is to either wait for all threads to complete...

$_->join for threads->list;

Or to detach all your threads, they will be terminated when the program exits.

$_->detach for threads->list;

Additionally, you want to use threads->list to get a list of all non-joined, non-detached threads, running or not. threads->list(threads::running) will only give you the threads which are still running. If any thread has completed but not been joined, it will be missed.

Upvotes: 2

Related Questions