Multithreading 带警报的Perl线程
有什么方法可以让警报(或其他超时机制)在perl(>=5.012)线程中工作吗?在主线程中运行Multithreading 带警报的Perl线程,multithreading,perl,timeout,Multithreading,Perl,Timeout,有什么方法可以让警报(或其他超时机制)在perl(>=5.012)线程中工作吗?在主线程中运行警报,并使用信号处理程序向活动线程发送信号 use threads; $t1 = threads->create( \&thread_that_might_hang ); $t2 = threads->create( \&thread_that_might_hang ); $SIG{ALRM} = sub { if ($t1->is_running) { $t1
警报,并使用信号处理程序向活动线程发送信号
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->是否可连接
,而不是调用$thr->join
当我尝试此解决方案时,它会挂起在我的系统上,并且警报从不熄灭。似乎join
阻止了SIGALRM。这是过去5年来的新行为吗?@CDahn我也有同样的问题。我们正在寻找一个非阻塞的thr->join()
,但是没有,所以现在我考虑使用thr->is_joinable()
轮询线程状态,这样我就不会阻塞SIGALRM