in reply to The problem on re-collection thread using join
What I have taken to doing is putting a FINISH: label at the end of the thread-code-block, and when I want to join a thread, I send it a die signal thru a shared variable. In the thread-code, test for the shared-var in your loop, and if "condition is met", put a "goto FINISH" in the statement. Then whenever you want to join the thread, you do 2 things, send the die, then join. I like using hashes to keep track of it all. Also, if you "detach" you can't join.
#!/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\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, 10) }; } FINISH: print "Thread ", $self->tid, " ending\n"; }
|
|---|