我有一個Perl腳本啓動2個線程,每個處理器一個。我需要它等待一個線程結束,如果一個線程結束了一個新線程的產生。看起來join方法阻塞了程序的其餘部分,因此,第二個線程不能結束,直到第一個線程完成的任何事情都完成了,這種方式會失敗它的目的。在Perl中,我該如何等待線程並行結束?
我試過is_joinable
方法,但似乎也沒有做到這一點。
下面是我的一些代碼:
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";
}
的這個輸出是:
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
今天你是我的上帝;)不錯的解決方案.. 還有一件事: 把鎖放在列表上我現在這樣做: if(1 == 1){lock(@file_list); $ file = shift(@file_list); } 我需要這個,如果它在運行函數前在最後解鎖。這似乎是一個很不錯的黑客,但:)更好的辦法嗎? – Pmarcoen 2010-03-16 12:16:50