我是新來的Perl,我有一個關於Perl線程的問題。如何在Perl中結束一個線程
我想創建一個新線程來檢查運行函數是否超時,我的做法如下。
邏輯是 1,創建一個新的線程 2.run主要功能,看看它是否超時,如果TURE,殺死它
示例代碼:
$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 =真正的作品,因爲有是while循環結尾處的「last」。
有人可以給我一個答案嗎?
感謝
請使用'strict'和'warnings'向我們展示一個簡短,完整的工作示例。 「true」和「false」不是Perl-ims,我不太理解你爲什麼要詢問* threads *,但顯示引用* remote processes *的代碼摘錄。 – pilcrow