Using async for threads in perl script I need to do some parallel functionality, however I have to set a fix time limit for such threads (e.g. max 5 sec). I need to kill all runing threads if they are running for longer, but still keep program alive. My code is:
use threads ( 'yield',
'exit' => 'threads_only',
'stack_size' => 2*16384 );
use threads::shared;
use Time::HiRes qw/sleep/;
...
$start = [Time::HiRes::gettimeofday()];
my $running :shared = 0;
foreach ($entry) {
async(
sub {
local $SIG{KILL} = sub { threads->exit };
{ lock $running; ++$running };
...
{ lock $running; --$running };
},
$_)->detach;
}
while ($running) {
sleep 0.005;
last if (Time::HiRes::tv_interval($start) > 5);
}
if ($running) {
my @running = threads->list(threads::running);
foreach (@running) {
$_->kill('KILL')->detach;
}
}
print "I am still alive\n";
Is there some better way how to kill running threads and keep application alive?
Don’t do it that way. Code the threads so that they only do work that you want done and terminate themselves when there’s no work for them to do. Don’t try to go in from the outside and kill them. That never works well.