gpt4 book ai didi

multithreading - 带有警报的 Perl 线程

转载 作者:行者123 更新时间:2023-12-03 22:44:11 25 4
gpt4 key购买 nike

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

最佳答案

运行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

关于multithreading - 带有警报的 Perl 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com