in reply to Re^2: wait for threads to end in parallel
in thread wait for threads to end in parallel
Ah, I see. I read is_joinable() in the code, but I didn't understand its significance. So the while loop polls each thread to discover when a thread is finished processing a file.
With some slight modifications of the op's code, the output shows that the threads do not appear to be waiting for each other (the code does get stuck in an infinite loop when the threads are done processing the files):
use strict; use warnings; use 5.010; use threads; use threads::shared; my @file_list = ( 'file1', 'file2', 'file3', 'file4', 'file5', ); my $nofiles = @file_list; #number of files my $currfile = 1; #current number of file to process my %MSG : shared; #shared hash my $thr0 = threads->new(\&process, shift(@file_list), 'thr0'); $currfile++; my $thr1 = threads->new(\&process, shift(@file_list), 'thr1'); $currfile++; while(1) { if ($thr0->is_joinable()) { $thr0->join; #check if there are files left to process if($currfile <= $nofiles){ $thr0 = threads->new(\&process, shift(@file_list), 'thr0'); $currfile++; } } if ($thr1->is_joinable()) { $thr1->join; #check if there are files left to process if($currfile <= $nofiles){ $thr1 = threads->new(\&process, shift(@file_list), 'thr1'); $currfile++; } } } sub process{ my($file, $thr_name) = @_; print "$thr_name opening $currfile of $nofiles\n"; #do some stuff sleep int(rand 5); print "$thr_name done with $currfile of $nofiles\n"; } --output:-- thr0 opening 1 of 5 thr1 opening 2 of 5 thr1 done with 2 of 5 thr1 opening 3 of 5 thr1 done with 3 of 5 thr1 opening 4 of 5 thr0 done with 1 of 5 thr0 opening 5 of 5 thr1 done with 4 of 5 thr0 done with 5 of 5
Ugh. That is really icky code.
|
|---|