2

我是 perl 新手,我对 perl 线程有疑问。

我正在尝试创建一个新线程来检查正在运行的函数是否超时,我的方法如下。

逻辑是 1.新建一个线程 2.运行main函数,看看是否超时,如果是,就kill掉

示例代码:

$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 是否有效,因为在 while 循环的末尾有一个“last”。

谁能给我一个答案?

谢谢

4

1 回答 1

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变量 - 它只会从调用它的点离开循环。

这是在回答你的问题吗?

于 2012-10-12T08:18:39.587 回答