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

Hi, I have a program where I spawn multiple threads in something like this
for $i (0..$number) { $thr_{$i} = new Thread \&sub_routine, arg1, @array_of args; } sub sub_routine { do something; return "Thread completed successfully"; }
This way I have multiple threads started. After this I want to wait for all threads to end, and then start processing the output files generated by the threads. Should I do something like this?
my @threads_return_data for $i (0 .. $number) { push @threads_return_data, $thr_{$i}->join; } post_processing_subroutine();

Replies are listed 'Best First'.
Re: help on threads
by zentara (Cardinal) on Mar 22, 2006 at 12:23 UTC
    I think the way you are joining will work, but it will wait in sequential order, for each thread to join. That is it will wait to join $thr_{0} then on to $thr_{1}, etc. It dosn't take into account which thread finishes first. In the case where you are waiting for ALL threads to finish, it dosn't matter.

    But there are cases where you want to detect which thread finishes first, then stop the others when that happens. You could also use a while loop to join each thread as they finish, if you were interested in the finish order, like:

    #!/usr/bin/perl use warnings; use strict; use threads; use threads::shared; $| = 1; my %threads; foreach (1..10){ share $threads{$_}{'die'}; share $threads{$_}{'data'}; $threads{$_}{'die'} = 0; $threads{$_}{'data'} = 0; } foreach (1..10) { $threads{$_}{'thread'} = threads->new('StartTest'); } my @threads = (1..10); while(1){ foreach my $t (@threads){ if($threads{$t}{'data'} > 5){ $threads{$t}{'die'} = 1; $threads{$t}{'thread'}->join; @threads = grep { $_ != $t } @threads; } } if(scalar @threads == 0){last} } 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{ print "From thread $self->",$threads{$_}{'data'}++,"\n"; sleep 1; }; } FINISH: print "Thread ", $self->tid, " ending\n"; }

    I'm not really a human, but I play one on earth. flash japh