假设我有 5 个文件,名为a到e。我想并行处理这些。我以为我可以做这样的事情:
my @ltrs = ('a'..'e');
for my $fnum (0..2) {
$pid = fork();
if ($pid) {
push(@childs, $pid);
}
elsif ($pid == 0) {
do {
my $ltr = shift(@ltrs);
print "Open file $ltr on $fnum\n";
} until (scalar(@ltrs)==0);
exit(0);
}
else {
die "Couldn't fork: $!\n";
}
}
foreach (@childs) {
waitpid($_, 0);
}
但是每个子进程都在访问以下所有五个元素@ltrs
:
Open file a on 0
Open file b on 0
Open file c on 0
Open file d on 0
Open file e on 0
Open file a on 1
Open file b on 1
Open file c on 1
Open file d on 1
Open file e on 1
Open file a on 2
Open file b on 2
Open file c on 2
Open file d on 2
Open file e on 2
当一个进程shift
从数组中获取一个元素时,为什么当下一个进程查看数组时该元素仍然存在?我假设在第一个之后shift
,接下来发生的任何过程都会找到一个以 开头的数组b
,但显然我错过了一些东西。