【发布时间】: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”。
谁能给我答案?
谢谢
【问题讨论】:
-
请向我们展示一个简短而完整的工作示例,使用
strict和warnings。 "true" 和 "false" 不是 Perl 主义,我不太明白你为什么问 threads 而是显示引用 remote processes 的代码摘录。
标签: multithreading perl