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?