带有警报的Perl线程

编程入门 行业动态 更新时间:2024-10-23 13:33:11
本文介绍了带有警报的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线程

本文发布于:2023-11-27 21:12:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   线程   Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!