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