Perl线程与警报

时间:2011-06-13 15:54:18

标签: multithreading perl timeout

有没有办法在perl(> = 5.012)线程中使用警报(或其他一些超时机制)?

1 个答案:

答案 0 :(得分:5)

在主线程中运行alarm,并使用一个信号处理程序来指示您的活动线程。

use threads;
$t1 = threads->create( \&thread_that_might_hang );
$t2 = threads->create( \&thread_that_might_hang );
$SIG{ALRM} = sub {
    if ($t1->is_running) { $t1->kill('ALRM'); }
    if ($t2->is_running) { $t2->kill('ALRM'); }
};

alarm 60;
# $t1->join; $t2->join;
sleep 1 until $t1->is_joinable; $t1->join;
sleep 1 until $t2->is_joinable; $t2->join;
...

sub thread_that_might_hang {
    $SIG{ALRM} = sub { 
        print threads->self->tid(), " got SIGALRM. Good bye.\n";
        threads->exit(1);
    };
    ... do something that might hang ...
}

如果您需要为每个线程提供不同的警报,请查看允许您设置多个警报的模块,例如Alarm::Concurrent


修改:评论员指出threads::join会干扰SIGALRM,因此您可能需要测试$thr->is_joinable而不是调用$thr->join