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 ...
}
Run Code Online (Sandbox Code Playgroud)
如果您需要为每个线程提供不同的警报,请查看允许您设置多个警报的模块Alarm::Concurrent.
编辑:评论员指出threads::join干扰SIGALRM,所以你可能需要测试$thr->is_joinable而不是调用$thr->join
| 归档时间: |
|
| 查看次数: |
2887 次 |
| 最近记录: |