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

Hi again, monks! I've been trying to finish my app but I'm trapped again in some tricks I still don't know well. This time I get the error "A thread exited while 2 threads were running" because I sent a 'return' before interrupting my thread. And that's my question. How to interrupt it?? I've searched CPAN, Perldocs.org and Google.com for this and had no success. My script opens a socket server and listens for 20 seconds, and then I have to stop listening it. How to do it to work? Thanks a lot. ;D

Replies are listed 'Best First'.
Re: Interrupting a Thread
by zentara (Cardinal) on Mar 20, 2006 at 21:43 UTC
    To avoid that error, you must "return from the thread" first, then join it. If the thread was detached, no need to join, but you won't be able to get a return value. So remember, the thread must

    1. Reach the end of it's code block(or return).

    2. Must be joined, unless it was detached.

    Here is a simple example, where I use a "goto FINISH" to force the thread to the end of it's code block, but I could have used "return". Now, if you want to kill a thread(s) prematurely, just set it's 'die' signal to one and join it.

    #!/usr/bin/perl use warnings; use strict; use threads; use threads::shared; $| = 1; my %threads; foreach (1..10){ share ($threads{$_}{'die'}); $threads{$_}{'die'} = 0; } foreach (1..10) { $threads{$_}{'thread'} = threads->new('StartTest'); } my @threads = (1..10); foreach(@threads){ $threads{$_}{'die'} = 1; $threads{$_}{'thread'}->join; } print "\n", "All threads done\nHit Enter to exit\n"; <>; ########################################################## sub StartTest { my $self = threads->self; print "Thread ", $self->tid, " started\n"; while(1){ if( $threads{$_}{'die'} == 1){goto FINISH} else{ select(undef,undef,undef, 5) }; } FINISH: print "Thread ", $self->tid, " ending\n"; }

    I'm not really a human, but I play one on earth. flash japh
Re: Interrupting a Thread
by theshz (Sexton) on Mar 20, 2006 at 20:36 UTC
    I believe this error usually happens when your main thread existed while the children are still running. You may want to use "$thread->join()" to wait for the children to finish.