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 但我该怎么做呢?我什至不确定这是否是问题所在。
I have a Perl script that launches threads while a certain expression is verified.
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
I guess I shall clean @threads but how can I do that? I am not even sure if this is the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在循环结束时清除
@threads
即可:或者更好的是,在循环开始时使用
my
声明@threads
:Just clear
@threads
at the end of the loop:Or better, declare
@threads
withmy
at the beginning of the loop:最简单的解决方案是在 while 循环内创建数组 (
while {my @threads; ...}
),除非您在其他地方需要它。否则,您可以在 while 循环末尾仅使用@threads = ()
或@threads = undef
。您还可以在 while 循环外部设置一个变量
my $next_thread;
,然后在 while 循环中首先分配$next_thread = @threads
并更改您的foreach< /code> 循环
或跳过它,然后循环遍历最后三个添加的线程的一部分
The easiest solution would be to create the array inside the while loop (
while {my @threads; ...}
), unless you need it anywhere else. Otherwise you could just@threads = ()
or@threads = undef
at the end of the while loop.You could also set a variable
my $next_thread;
outside the while loop and then assign$next_thread = @threads
first thing in the while loop and change yourforeach
loop toor skip that and just loop over a slice of the last three added threads