簡體   English   中英

在Perl中完成線程后如何清理它們?

[英]How to cleanup threads once they have finished in Perl?

我有一個Perl腳本,可以在驗證特定表達式的同時啟動線程。

while ($launcher == 1) {
    # do something
    push @threads, threads ->create(\&proxy, $parameters);
    push @threads, threads ->create(\&ping, $parameters);
    push @threads, threads ->create(\&dns, $parameters);
    # more threads
    foreach (@threads) {
    $_->join();
    }
}

第一個循環運行良好,但是在第二個循環中,腳本退出並顯示以下錯誤:

線程已在launcher.pl第290行加入。Perl退出並帶有活動線程:1正在運行且未加入0已完成且未加入0正在運行並已分離

我想我應該清理@threads,但是我該怎么做呢? 我什至不確定這是否是問題。

只需在循環結束時清除@threads

@threads = ();

或者更好的是,在循環開始時用my聲明@threads

while ($launcher == 1) {
    my @threads;

最簡單的解決方案是在while循環( while {my @threads; ...} )內創建數組,除非您在其他任何地方都需要它。 否則,您可以在while循環結束時使用@threads = ()@threads = undef

您還可以在my $next_thread;設置一個變量my $next_thread; 在while循環外,然后在while循環中分配$next_thread = @threads第一件事,並將您的foreach循環更改為

for my $index ($next_thread .. $#threads) {
    $threads[$index]->join();
}

或跳過它,然后循環遍歷最后三個已添加線程的一部分

for (@threads[-3..-1) {
    $_->join();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM