Home: Perl Programming Help: Advanced:
Kill the current thread and continue with main program



vivekchamp103
New User

May 23, 2015, 7:31 PM


Views: 7773
Kill the current thread and continue with main program

Hi,
I am trying to write a perl script, where it should perform some task using thread and after some time (timeout) if thread is not done with the task, it should get killed and continue with main program.
my sample program is here:
==================

Code
#!perl 
use threads;
my $thr = threads->create(sub {
threads->yield();

$SIG{'KILL'} = sub {
threads->exit();
};
sleep(25);

});
my $timeout=10;
my $counter=0;
while (1){
if ($thr->is_running()){
if ($counter != $timeout){
$counter++;
sleep 1;
print "$counter, is running:\n";
}
else {
print "inside else\n";
$threads->kill('KILL');
}
}
else {
last;
}
}
print "print this first\n";
$thr->join();
print "print this last \n";

===================
What I am expecting here is after threads killed, program should print "print this last".


(This post was edited by FishMonger on May 24, 2015, 8:54 AM)


FishMonger
Veteran / Moderator

May 24, 2015, 9:51 AM


Views: 7760
Re: [vivekchamp103] Kill the current thread and continue with main program

I have not done any testing using the threads module, but if you add the strict and warnings pragmas (which should be in every script), you will see one of the problems.


FishMonger
Veteran / Moderator

May 24, 2015, 10:14 AM


Views: 7755
Re: [vivekchamp103] Kill the current thread and continue with main program

Once you fix the compilation error, the script will work as expected, but I'd reduce the sleep value in the subroutine to no more than 15. I think the ideal sleep value is the same as the timeout.


Code
#!/perl 

use strict;
use warnings;
use threads;

my $timeout=10;
my $thr = threads->create(sub {
threads->yield();
local $SIG{'KILL'} = sub {
threads->exit();
};
sleep($timeout);
});


my $counter=0;
while (1){
if ($thr->is_running()){
if ($counter != $timeout){
$counter++;
sleep 1;
print "$counter, is running:\n";
}
else {
print "inside else\n";
$thr->kill('KILL');
}
}
else {
last;
}
}
print "print this first\n";
$thr->join();
print "print this last \n";



(This post was edited by FishMonger on May 24, 2015, 10:17 AM)


vivekchamp103
New User

May 24, 2015, 10:39 AM


Views: 7750
Re: [FishMonger] Kill the current thread and continue with main program

Hi,
Thanks for your reply, but what i am looking here is script gets timeout and thread gets killed before the sleep time in thread and my main program continues. if timeout and sleep (in thread) is same then what is need of thread killing ?
Thanks,
ViveK