带警报的 Perl 线程

发布于 2024-11-15 02:56:21 字数 50 浏览 1 评论 0原文

有没有办法让警报(或其他超时机制)在 perl (>=5.012) 线程中工作?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月打碎记忆 2024-11-22 02:56:21

在主线程中运行 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->加入

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 ...
}

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


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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文