On 22 May 2007 15:44:28 GMT,
wrote:
>zentara <> wrote:
>>
>> Here is an example I have of an ALARM in a thread. It works for me,
>> but it may not be what you are looking for.
>
>What OS and what version of Perl are you using?
>Your code doesn't work for me. The main program is blown away by
>the alarm, without catching it in the SIG{ALRM} and without
>clobbering the z1 process, which just keeps on running.
>
>This is perl, v5.8.3 built for x86_64-linux-thread-multi
>
>Thanks,
>Xho
You are right, I'm totally wrong. I'll have to mark that one as
non-working too.
I may have first tested in back in the Perl5.6 days, but it dosn't
work now.

Maybe it never worked, but I was too dumb to
notice.

Sorry for the confusion.
It seems that setting alarm in the thread will kill the main thread.
Try this, where I set the alarm callback in main, it works. So you
should be able to work around it. Of course if you want to have separate
alarms in multiple threads, you are SOL. The only thing you can do in
that case, is have secondary timer threads instead of alarm, OR use
an event loop system in your main thread, that can timeout the thread
by running it's own timer.
To be honest, I never even use alarm anymore, I setup my own timers,
since I generally use Tk, or Gtk2. (POE would work too).
Gtk2's GLib will setup timers even in non-gui programs, as will POE.
Tk has to be a GUI.
#!/usr/bin/perl
use warnings;
use strict;
use threads;
use threads::shared;
# ALARM DOSN"T WORK WELL IN THREADS
my $waitTime : shared;
my $done : shared;
my $child_pid : shared;
$waitTime = 5;
$done = 0;
my $cmd = './z1';
my $thr = threads->new(\&my_exec_thread, $cmd);
$SIG{ALRM} = sub { warn "thread timeout\n";
kill 9, "$child_pid\n";
};
while(1){
if ( $done == 1 ) {
print "Thread completed \n";
$thr->join;
last;
}elsif ( $done eq 'TIMED OUT' ) {
print "Thread Timed OUT\n";
$thr->join;
last;
}else{next}
}
print "1\n";
################################################## ####
sub my_exec_thread {
my $cmd = shift;
print ("In thread ".$cmd."\n");
###########################################
# will kill it all, even main thread with message ALARM CLOCK
#$SIG{ALRM} = sub { warn "thread timeout\n";
# kill 9, "$child_pid\n";
# };
############################################
eval {
alarm($waitTime);
unless ($child_pid = fork) {
exec $cmd;
die "could not exec $cmd: $!";
}
print "pid->$child_pid\n";
wait;
alarm(0);
};
print "--------- $@\n";
print "end of thread code block , main lives on\n";
}
__END__
zentara
--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html