Perl线程与警报

cir*_*100 4 perl multithreading timeout

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

mob*_*mob 6

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

  • 当我尝试这个解决方案时,它挂在我的系统上,并且`alarm`永远不会消失.似乎`join`阻止了SIGALRM.这是过去5年的新举措吗? (3认同)