2
votes

I have a Perl script that spawns a group of worker threads. When one of these threads encounters a fatal error I would like the ENTIRE script to die and print an error message.

The problem is... when you use die in a thread it will only terminate the current thread with a message like Thread 42 terminated abnormally: blah blah blah... and the rest of the script will continue to run.


Example:

use strict;
use warnings;
use threads;

# Create threads
for my $i (1 .. 5) {
    threads->create(\&do_something, $i);
}

# Wait for all threads to complete
$_->join() for threads->list();

sub do_something {
    my $i = shift;
    die "I'm died" if $i == 3;
}

Output:

Thread 3 terminated abnormally: I'm died at line 15


How can I make a fatal error in a thread kill the whole script?

1

1 Answers

4
votes

According to perldoc threads:

Calling exit EXPR inside a thread causes the whole application to terminate. Because of this, the use of exit() inside threaded code, or in modules that might be used in threaded applications, is strongly discouraged.

If exit() really is needed, then consider using the following:

threads->exit() if threads->can('exit');   # Thread friendly
exit(status);