2012-10-11 30 views
2

我是新來的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」。

有人可以給我一個答案嗎?

感謝

+0

請使用'strict'和'warnings'向我們展示一個簡短,完整的工作示例。 「true」和「false」不是Perl-ims,我不太理解你爲什麼要詢問* threads *,但顯示引用* remote processes *的代碼摘錄。 – pilcrow

回答

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變量 - 它會簡單地從調用它的點退出循環。

這是回答你的問題嗎?

+0

感謝您的回答。我想說的是變量「$ exit_timeout」,我設置它的目的是確保超時線程在不需要時終止。但正如你所看到的,我在while循環結束時放置了一個「last」,以確保超時線程將被終止,無論是執行主函數還是超時,這意味着超時線程在我設置「$ exit_timeout 「到」真「。所以只是想知道是否需要「$ exit_timeout」。 – user1672190

+0

變量'$ exit_timeout'是什麼意思?代碼中沒有這樣的變量 –