Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Perl, how can I wait for threads to end in parallel?
    text
    copied!<p>I have a Perl script that launches 2 threads,one for each processor. I need it to wait for a thread to end, if one thread ends a new one is spawned. It seems that the join method blocks the rest of the program, therefore the second thread can't end until everything the first thread does is done which sort of defeats its purpose.</p> <p>I tried the <code>is_joinable</code> method but that doesn't seem to do it either.</p> <p>Here is some of my code :</p> <pre><code>use threads; use threads::shared; @file_list = @ARGV; #Our file list $nofiles = $#file_list + 1; #Real number of files $currfile = 1; #Current number of file to process my %MSG : shared; #shared hash $thr0 = threads-&gt;new(\&amp;process, shift(@file_list)); $currfile++; $thr1 = threads-&gt;new(\&amp;process, shift(@file_list)); $currfile++; while(1){ if ($thr0-&gt;is_joinable()) { $thr0-&gt;join; #check if there are files left to process if($currfile &lt;= $nofiles){ $thr0 = threads-&gt;new(\&amp;process, shift(@file_list)); $currfile++; } } if ($thr1-&gt;is_joinable()) { $thr1-&gt;join; #check if there are files left to process if($currfile &lt;= $nofiles){ $thr1 = threads-&gt;new(\&amp;process, shift(@file_list)); $currfile++; } } } sub process{ print "Opening $currfile of $nofiles\n"; #do some stuff if(some condition){ lock(%MSG); #write stuff to hash } print "Closing $currfile of $nofiles\n"; } </code></pre> <p>The output of this is :</p> <pre><code>Opening 1 of 4 Opening 2 of 4 Closing 1 of 4 Opening 3 of 4 Closing 3 of 4 Opening 4 of 4 Closing 2 of 4 Closing 4 of 4 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload