【问题标题】:Perl threads kill timeout threadPerl 线程杀死超时线程
【发布时间】:2015-10-30 22:20:21
【问题描述】:

我有一个使用 threads 的多线程 perl 脚本,工作正常,但是当它试图杀死挂起的线程时,我收到错误并且脚本存在:

for (0..$threads-1) {
        $trl[$_] = threads->create(\&my_sub, $_);
        $SIG{ALRM} = sub {
                if ($trl->is_running) {
                   $trl->kill('ALRM');
                }
        }
}
for (@trl) {
        alarm 10;
        $_->join;
}

sub my_sub {
  $SIG{ALRM} = sub {
        threads->exit(1);
  };
  while (@site) {
  {
        lock(@site);
        $url = shift @site;
  }

和错误:

Can't call method "is_running" on an undefined value at test.pl line 61.
Perl exited with active threads:
        9 running and unjoined
        40 finished and unjoined
        0 running and detached

第 61 行是:

if ($trl->is_running) {

【问题讨论】:

    标签: perl


    【解决方案1】:

    好的,请开启strictwarnings。这会告诉你@trl$trl 不是一回事。具体来说 - 您的 main 程序中的“信号处理程序” - 每次启动线程时都会重新定义,因此它只会杀死最新的线程。 (除非它不会,因为 $tr1 未定义)。

    我建议您无论如何都不要混合信号和线程 - 这更多地取决于您在做什么。但通常我会建议 - forkkillthreadThread::SemaphoreThread::Queue

    【讨论】:

    • 谢谢!我会尝试Thread::Semaphore,无论如何我应该如何正确设置脚本旁边的行if ($trl->is_running) { 不能这样运行?
    • 我无法回答,因为你不能按照你想做的方式去做你想做的事。我建议您考虑使用Thread::Queue 将您的网站提供给您的潜艇,而不是使用全局数组。例如。在这个例子中是这样的:stackoverflow.com/questions/26296206/…
    • 谢谢!无论如何我明白了,该行应该是if ($_->is_running) {
    • 是的,但是说真的 - 这不起作用,因为在调用信号处理程序时 $_ 是未定义的。那会很糟糕。
    猜你喜欢
    • 2016-07-10
    • 2014-05-10
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多