带有警报的Perl线程 [英] Perl threads with alarm

查看:75
本文介绍了带有警报的Perl线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使警报(或其他超时机制)在perl(> = 5.012)线程中工作吗?

Is there any way to get alarm (or some other timeout mechanism) working in perl (>=5.012) threads?

推荐答案

在主线程中运行alarm,并使用信号处理程序向活动线程发送信号.

Run alarm in your main thread, with a signal handler that signals your active threads.

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.

If you need different alarms for each thread, look into a module that allows you to set multiple alarms like Alarm::Concurrent.

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

commentors point out threads::join interferes with SIGALRM, so you may need to test $thr->is_joinable rather than calling $thr->join

这篇关于带有警报的Perl线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆