Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm wondering if it's possible to continue in my same method call after I've killed the thread. Currently I call a sub that spawns a new thread and once the thread has done it's job it gets killed. My issue is that I'm unable to continue in the initial thread call after it has been killed. I hope that makes sense. Here is what I'm doing:
use threads; use threads::shared; use Thread::Queue; # Signal Handler $SIG{'KILL'} = sub { # Tell user we've been terminated printf(" %3d <- Killed\n", threads->tid()); # Detach and terminate threads->detach() if ! threads->is_detached(); threads->exit(); }; StartThread(); sub StartThread { my @threads = threads->list(); # Check to see if there any running threads foreach ( @threads ) { print "Killing thread ... "; $_->kill('KILL'); print "Done\n"; } # Spawn new thread my $worker = threads->create(\&StartTest ); } sub StartTest { for ( 0..10 ) { print "I: $_\n"; } StartThread(); }
I'm trying to create a new thread by calling the StartThread after it prints to 10.

Replies are listed 'Best First'.
Re: continue after killing thread?
by zwon (Abbot) on Dec 18, 2009 at 21:42 UTC

    You actually doesn't try to continue in the main thread. And BTW do you really understand what is your program doing? I've added some debugging output, so you could see that your program doesn't run many threads:

    use strict; use warnings; use threads; # Signal Handler $SIG{'KILL'} = sub { printf( " %3d <- Killed\n", threads->tid() ); threads->exit(); }; StartThread(); while (1) { warn "Here we continue in main thread"; sleep 1; } sub StartThread { # actually "Starting thread" is not correct here warn "Starting thread ", threads->tid, "\n"; my @threads = threads->list(); warn "Threads to kill: ", join ',', map { $_->tid } @threads; # Check to see if there any running threads # Note, that only main thread can survive this loop # any other thread will kill itself foreach (@threads) { print "Killing thread ... "; $_->kill('KILL'); print "Done\n"; } # Spawn new thread my $worker = threads->create( \&StartTest ); warn "exiting thread ", threads->tid; } sub StartTest { print "I: $_\n" for ( 0 .. 10 ); StartThread(); } __END__ Starting thread 0 Threads to kill: at 813428.pl line 22. exiting thread 0 at 813428.pl line 33. Here we continue in main thread at 813428.pl line 15. I: 0 I: 1 I: 2 I: 3 I: 4 I: 5 I: 6 I: 7 I: 8 I: 9 I: 10 Starting thread 1 Threads to kill: 1 at 813428.pl line 22. Killing thread ... 1 <- Killed Here we continue in main thread at 813428.pl line 15. Here we continue in main thread at 813428.pl line 15. Here we continue in main thread at 813428.pl line 15. ^C
    So you starting only one thread, which prints ten numbers and kills itself. Main thread without problems continue to run while(1) loop.