2

免责声明:今天的硬件就是这样,我已经有一段时间不用分叉了,所以我可能需要一些关于以下代码的建议。下面也是一个简单的例子,不是实际的代码。

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为线程提供原生途径?

4

1 回答 1

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
于 2013-05-25T14:41:45.977 回答