multithreading - Perl: fork 和填充父数组

标签 multithreading perl fork

免责声明:鉴于今天的硬件已经足够,所以我不必花一会儿时间,因此我可能需要有关以下代码的一些建议。以下也是一个简单示例,而不是实际代码。

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/

相关文章:

Perl - 哈希和 => 运算符

perl - 在 Perl 中使用引用指向滑动窗口数组

c - 为什么子进程在使用父输出的标准输入的 fork 和管道时等待?

c - 使用 fork() 产生内存映射

Java:ExecutorService 的效率不如手动线程执行?

c++ - 线程合并排序给出无效结果

android - 为什么打开 proguard 的 "Surface frame wait timed out"编码?

perl - 有什么好的 Perl 自动化测试套件吗?

c - 这段代码打印什么?循环中的 fork

c++ - 基于 Qt 的 CD 开膛手的线程构建 block (TBB)?