Ho uno script Perl che avvia 2 thread, uno per ciascun processore. Ho bisogno di aspettare che un thread finisca, se un thread termina ne viene generato uno nuovo. Sembra che il metodo di join blocchi il resto del programma, quindi il secondo thread non può finire fino a quando non viene eseguito tutto il primo thread che sconfigge il suo scopo.In Perl, come posso aspettare che i thread terminino in parallelo?
Ho provato il metodo is_joinable
ma non sembra neanche farlo.
Ecco alcuni del mio codice:
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->new(\&process, shift(@file_list));
$currfile++;
$thr1 = threads->new(\&process, shift(@file_list));
$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));
$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));
$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";
}
L'output di questo è:
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
Oggi sei il mio dio;) bella soluzione .. Un'altra cosa: Per mettere i blocchi sulla lista Ora faccio questo: if (1 == 1) {lock (@file_list); $ file = shift (@file_list); } Ho bisogno di questo se è stato sbloccato alla fine prima di eseguire la funzione. Questo sembra un bel noob-hack però :) in qualche modo migliore? – Pmarcoen