In Perl, there are several different ways to kill thread , depending on what you want to achieve.
Take the following code as an example:
use strict; use warnings; use threads; use Thread::Queue;
In the above code, 3 threads are created, each of which will receive and process the element of the general queue until the queue is empty.
In this case, since we announced that no more elements will be added to the queue (for example, $ queue-> end ()), the threads will be connected (to the main one) after they have processed all the elements in the queue. In fact, using $ thread-> join (), we tell the main thing to wait for $ thread to join.
If we omit declaring $ queue-> end (), the threads will not join the main one, but will remain pending for new queue elements.
Now, if we want to kill streams, we have two options: kill streams, but letting them finish what they do first or simply (brutally) by killing streams immediately. In Perl, both are achieved using Thread Signaling .
In the first case (that is, if we want the threads to finish working, and then to stop processing the shared queue), we should use $ thread-> kill ('KILL') → join ():
foreach my $thread ( threads->list() ) {
On the other hand, in the latter case (i.e. if we want to kill the threads immediately), we must use $ thread-> kill ('KILL') → kill ():
foreach my $thread ( threads->list() ) {
Of course, if you want to kill the thread from the inside, you just need to call threads-> exit () or just use return :
sub do { ... threads->exit();