Her işlemcinin biri olmak üzere 2 iş parçacığı başlatan bir Perl betiğim var. Bir iş parçacığının bitmesini beklemek gerekiyor, eğer bir iş parçacığı biterse yeni bir yumurtlanırsa. Görünüşe göre, birleştirme yöntemi programın geri kalanını engeller, bu nedenle ikinci iş parçacığı, ilk iş parçacığının yaptığı her şey bitene kadar sona ermez.Perl'de, iş parçacığının paralel olarak bitmesini nasıl bekleyebilirim?
is_joinable
yöntemini denedim, ancak bu da öyle görünmüyor. İşte
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";
}
bu çıktısı:
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
Bugün sen benim tanrımsın;) güzel bir çözüm .. Bir şey daha: Kilitleri listeye koymak için şimdi şunu yapın: (1 == 1) {lock (@file_list); $ file = shift (@file_list); } Eğer işlevi çalıştırmadan önce sonunda kilidi açılacaksa buna ihtiyacım var. Bu güzel bir noob-hack gibi görünüyor :) ama daha iyi bir yolu? – Pmarcoen