[英]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.