[英]How to cleanup threads once they have finished in Perl?
I have a Perl script that launches threads while a certain expression is verified. 我有一个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();
}
}
The first cycle runs fine but at the second one the script exits with the following error: 第一个循环运行良好,但是在第二个循环中,脚本退出并显示以下错误:
Thread already joined at launcher.pl line 290. Perl exited with active threads: 1 running and unjoined 0 finished and unjoined 0 running and detached
线程已在launcher.pl第290行加入。Perl退出并带有活动线程:1正在运行且未加入0已完成且未加入0正在运行并已分离
I guess I shall clean @threads but how can I do that? 我想我应该清理@threads,但是我该怎么做呢? I am not even sure if this is the problem.
我什至不确定这是否是问题。
Just clear @threads
at the end of the loop: 只需在循环结束时清除
@threads
:
@threads = ();
Or better, declare @threads
with my
at the beginning of the loop: 或者更好的是,在循环开始时用
my
声明@threads
:
while ($launcher == 1) {
my @threads;
The easiest solution would be to create the array inside the while loop ( while {my @threads; ...}
), unless you need it anywhere else. 最简单的解决方案是在while循环(
while {my @threads; ...}
)内创建数组,除非您在其他任何地方都需要它。 Otherwise you could just @threads = ()
or @threads = undef
at the end of the while loop. 否则,您可以在while循环结束时使用
@threads = ()
或@threads = undef
。
You could also set a variable my $next_thread;
您还可以在
my $next_thread;
设置一个变量my $next_thread;
outside the while loop and then assign $next_thread = @threads
first thing in the while loop and change your foreach
loop to 在while循环外,然后在while循环中分配
$next_thread = @threads
第一件事,并将您的foreach
循环更改为
for my $index ($next_thread .. $#threads) {
$threads[$index]->join();
}
or skip that and just loop over a slice of the last three added threads 或跳过它,然后循环遍历最后三个已添加线程的一部分
for (@threads[-3..-1) {
$_->join();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.