【问题标题】:How to cleanup threads once they have finished in Perl?在 Perl 中完成后如何清理线程?
【发布时间】:2011-11-30 11:28:23
【问题描述】:

我有一个 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[0..2]。然后你尝试加入@threads[0..5],其中三个线程已经加入了。

标签: multithreading perl


【解决方案1】:

在循环结束时清除@threads

@threads = ();

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

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

【讨论】:

  • 我猜你说得比我更优雅。不过,您提到的@threads 有一个错字。
  • 这确实有效!我不知道为什么,但我认为这比那更困难,哈哈,非常感谢!
【解决方案2】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2019-07-09
    • 2012-03-25
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2017-05-15
    相关资源
    最近更新 更多