免责声明:今天的硬件就是这样,我不需要花一段时间,所以我可能需要一些关于以下代码的建议。以下是一个简单的例子,而不是实际的代码。
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
有一些匹配,并且@matched
正在填充,但是从我记忆中,fork
创建了父母的副本和我不知道的内容(我不确定是否我曾经这样做是如何访问父母的资源。我认为更简单的方法是在文件系统上创建一个临时文件,但我想避免任何外部文件。
是否有替代fork
为线程提供本机途径?
答案 0 :(得分:1)
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