gpt4 book ai didi

multithreading - Perl中的线程超时

转载 作者:行者123 更新时间:2023-12-03 13:00:17 26 4
gpt4 key购买 nike

我正在编写一个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 )
{
}

}

最佳答案

Documentation says

如果要使用警报使系统调用超时,则需要使用评估/模具对。

或者,您可以使用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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com