Alarm Pearl Streams

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

+3
source share
1 answer

Run alarmin 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;

...

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 several alarms, for example Alarm::Concurrent.

+5
source

All Articles