我是perl的新手,我对perl线程有疑问。
我正在尝试创建一个新线程来检查正在运行的函数是否超时,我的方法如下所示。
逻辑是 1.创建一个新线程 2.运行主要功能,看它是否超时,如果真的,杀了它
示例代码:
$exit_tread = false; # a flag to make sure timeout thread will run
my $thr_timeout = threads->new( \&timeout );
execute main function here;
$exit_thread = true # set the flag to true to force thread ends
$thr_timeout->join(); #wait for the timeout thread ends
超时功能代码
sub timeout
{
$timeout = false;
my $start_time = time();
while (!$exit_thread)
{
sleep(1);
last if (main function is executed);
if (time() - $start_time >= configured time )
{
logmsg "process is killed as request timed out";
_kill_remote_process();
$timeout = true;
last;
}
}
}
现在代码按照我的预期运行,但我不太清楚代码$ exit_thread = true是否有效,因为有一个" last"在while循环结束时。
有人可以给我一个答案吗?
由于
答案 0 :(得分:0)
假设正确的伪代码是这样的:
sub timeout
{
$timeout = false;
my $start_time = time();
#$timeout instead of $exit_thread
while (!$timeout)
{
sleep(1);
last if (main function is executed);
if (time() - $start_time >= configured time )
{
logmsg "process is killed as request timed out";
_kill_remote_process();
$timeout= true;
last;
}
}
}
然后,不,调用last
不会设置$timeout
变量 - 它只会让循环从调用它开始。
这是回答你的问题吗?