【问题标题】:How to end a thread in perlperl如何结束一个线程
【发布时间】:2012-10-11 21:33:50
【问题描述】:

我是 perl 新手,我有一个关于 perl 线程的问题。

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

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

示例代码:

$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”。

谁能给我答案?

谢谢

【问题讨论】:

  • 请向我们展示一个简短而完整的工作示例,使用strictwarnings。 "true" 和 "false" 不是 Perl 主义,我不太明白你为什么问 threads 而是显示引用 remote processes 的代码摘录。

标签: multithreading perl


【解决方案1】:

假设正确的伪代码是这样的:

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

这是在回答你的问题吗?

【讨论】:

  • 感谢您的回答。我的意思是变量“$exit_timeout”,我设置它的目的是确保超时线程在不需要时终止。但是正如你所看到的,我在 while 循环的末尾放了一个“last”,以确保超时线程将被终止,无论是主函数执行还是超时,这意味着超时线程甚至在我设置“$exit_timeout”之前就完成了”到“真实”。所以只是想知道是否需要“$exit_timeout”。
  • 变量$exit_timeout是什么意思?您的代码中没有这样的变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 2020-09-21
  • 2022-11-16
  • 1970-01-01
相关资源
最近更新 更多