我正在编写一个 perl 脚本,以便在 5 秒后退出线程,如下所示。但我无法打印 if 条件中的消息。
脚本的输出是闹钟
当线程超时时,如何从父进程打印正确的错误消息。
#!/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 )
{
}
}
最佳答案
如果您想使用警报来使系统调用超时,您需要使用 eval/die 对。
或者,您可以使用 Sys::SigAction 并执行如下操作
use Sys::SigAction qw( timeout_call );
if ( timeout_call( 5 ,sub { $retval = DoSomething( @args ); } )
{
print "DoSomething() timed out\n" ;
}
编辑:参见暴徒对问题的回答:Perl threads with alarm
另请参阅 thread safe alarms 上的讨论.
关于multithreading - Perl 中线程的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359316/