Tengo un script Perl que inicia 2 hilos, uno para cada procesador. Necesito que espere a que termine un hilo, si un hilo termina uno nuevo se genera. Parece que el método de unión bloquea el resto del programa, por lo tanto, el segundo subproceso no puede finalizar hasta que todo lo que hace el primer subproceso termine, lo que de alguna manera frustra su propósito.En Perl, ¿cómo puedo esperar a que los hilos terminen en paralelo?
Probé el método is_joinable
pero eso tampoco parece hacerlo.
Aquí es parte de mi código:
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";
}
La salida de este es:
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
Hoy eres mi dios;) buena solución .. Una cosa más: Para poner los bloqueos en la lista ahora hago esto: if (1 == 1) {lock (@file_list); $ file = shift (@file_list); } Necesito esto si es así para que se desbloquee al final antes de ejecutar la función. Esto parece un bonito noob-hack :) ¿alguna forma mejor? – Pmarcoen