Reputation: 59
I am writing a perl script to exit a thread after 5sec as shown below. but I am not able to print the message from if condition.
Output of the script is Alarm clock
How to print proper error messages from the parent process when timeout for threads.
#!/usr/bin/perl
use strict;
use warnings;
use threads;
my $th = threads->create( \&sub1 );
my $thid = $th->tid();
eval
{
$SIG{'KILL'} = sub
{
if ( $th->is_running() )
{
print "timed out, exiting the thread $thid\n";
$th->exit();
}
};
alarm(5);
$th->join();
};
sub sub1
{
my $i = 0;
while ( $i == 0 )
{
}
}
Upvotes: 2
Views: 1672
Reputation: 21666
If you want to use alarm to time out a system call you need to use an eval/die pair.
Alternatively you can use Sys::SigAction and do something like below
use Sys::SigAction qw( timeout_call );
if ( timeout_call( 5 ,sub { $retval = DoSomething( @args ); } )
{
print "DoSomething() timed out\n" ;
}
Edit: See the answer of mob to the question: Perl threads with alarm
Also see the discussion on thread safe alarms.
Upvotes: 2