How can I kill a Perl thread immediately without killing the whole program?

When I use exit or die , it kills the whole program.

 foreach my $t (threads->list()) { $t->exit; $count++; } Usage: threads->exit(status) at main.pl line 265 Perl exited with active threads: 9 running and unjoined 0 finished and unjoined 0 running and detached 

Any ideas?

+4
source share
3 answers

To ignore the thread that is running, return control and throw away everything that it can output, the correct method to use is detach , not exit .

See perldoc perlthrtut - Ignoring a stream .


perldoc threads explains why the code exits:

 threads->exit() 

If necessary, a thread can be displayed at any time by calling threads->exit() . This will cause the stream to return undef in a scalar context or an empty list in the list context. When called from the main thread, it behaves the same as exit(0) .


Perhaps there is a way to achieve instant completion (does not work for me on Windows):

 use threads 'exit' => 'threads_only'; 

This globally overrides the default behavior of the exit() call inside the thread and effectively makes such calls behave the same as threads->exit() . In other words, with this setting, calling exit() only causes the thread to terminate. Due to its global effect, this setting should not be used inside modules or the like. This parameter does not affect the main thread.

The documentation also offers another way using the set_thread_exit_only method (again, does not work for me on Windows):

 $thr->set_thread_exit_only(boolean) 

This can be used to change the behavior of the output stream only for the stream after it is created. With a true argument, exit() will only result in a stream to exit. With a false argument exit() will terminate the application. This call does not affect the main thread.


The following example uses the kill signal to terminate the $unwanted stream:

 use strict; use warnings; use threads; my $unwanted = threads->create( sub { local $SIG{KILL} = sub { threads->exit }; sleep 5; print "Don't print me!\n"; } ); my $valid = threads->create( sub { sleep 2; print "This will print!\n"; } ); $unwanted->kill('KILL')->detach; # Kills $thr, cleans up $valid->join; # sleep 2, 'This will print!' 
+7
source

If you want to kill a thread, you kill it with $thread->kill . If you want to disable the thread, but leave it $thread->detach , use $thread->detach . threads->exit causes the current thread to exit; it does not accept a stream as invocant.

+3
source

The error message tells you that $t->exit requires an argument. Try to give him one. ( perldoc Threads seems like it isn't, but I don't know which package you are using.)

0
source

All Articles