免责声明:鉴于今天的硬件已经足够,所以我不必花一会儿时间,因此我可能需要有关以下代码的一些建议。以下也是一个简单示例,而不是实际代码。
my @matched;
my @names = qw/jim john sally/;
foreach my $name (@names) {
my $pid;
next if $pid = fork; # child birth
croak "Fork failed: $!" if not defined $pid; # terminate if child wasn't born
my $result = `command_to_get_some_list_of_names`; # sam sue john tyler
my @list = split /\s/, $result;
foreach my $match ( @list ){
push(@matched,$match) if $name eq $match; # where want to access parent array
}
exit; # child funeral
}
1 while (wait() != -1); # wait for children to finish playing
say "Matched: @matched"; # nothing; not desired, but expected
进行了匹配,并且在 child 中填充了
@matched
,但是据我所记得,fork
创建了父级的副本,而我不知道(不确定是否曾经做过)的是如何访问父级的资源。我认为更简单的方法是在文件系统上创建一个临时文件,但我想避免任何外部操作。fork
是否有替代方法可以提供 native 线程途径?
最佳答案
带有 Forks::Super
选项的 share
使此操作非常简单:
use Carp;
use 5.012;
use Forks::Super;
my @matched;
my @names = qw/jim john sally/;
foreach my $name (@names) {
my $pid = fork {
share => [ \@matched ],
sub => sub {
#croak "Fork failed: $!" if not defined $pid;
my $result = "sam sue john tyler"; # sam sue john tyler
my @list = split /\s/, $result;
foreach my $match ( @list ){
push(@matched,$match) if $name eq $match; # where want to access parent array
}
}
};
}
waitall; # wait for children to finish playing
say "Matched: @matched"; # nothing; not desired,
结果:
Matched: john
关于multithreading - Perl: fork 和填充父数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743540/