【发布时间】:2010-03-16 10:09:04
【问题描述】:
我有一个 Perl 脚本,它启动 2 个线程,每个处理器一个。我需要它等待一个线程结束,如果一个线程结束,就会产生一个新线程。似乎 join 方法阻塞了程序的其余部分,因此第二个线程无法结束,直到第一个线程所做的所有事情都完成了,这有点违背了它的目的。
我尝试了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
【问题讨论】:
标签: multithreading perl join locking