Perl 中线程完成后如何清理线程?

发布于 2024-12-19 01:36:00 字数 577 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方觉久 2024-12-26 01:36:00

只需在循环结束时清除 @threads 即可:

@threads = ();

或者更好的是,在循环开始时使用 my 声明 @threads

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

Just clear @threads at the end of the loop:

@threads = ();

Or better, declare @threads with my at the beginning of the loop:

while ($launcher == 1) {
    my @threads;
打小就很酷 2024-12-26 01:36:00

最简单的解决方案是在 while 循环内创建数组 (while {my @threads; ...}),除非您在其他地方需要它。否则,您可以在 while 循环末尾仅使用 @threads = ()@threads = undef

您还可以在 while 循环外部设置一个变量 my $next_thread; ,然后在 while 循环中首先分配 $next_thread = @threads 并更改您的 foreach< /code> 循环

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

或跳过它,然后循环遍历最后三个添加的线程的一部分

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

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 your foreach loop to

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文