如何在Perl中使用fork()?

itz*_*tzy 6 perl fork

我在数组中有数百个文件名.我想为数组中的每4个文件创建一个子进程,并让该子进程为这4个文件中的每一个做一些事情.(因此,对于100个文件,我将创建25个进程.)

我在理解有叉子时处理线的顺序时遇到了一些麻烦.我以为我可以做这样的事情,但我遇到了困难:

foreach $file (@files) {
 if ($f++ % 4 == 0) {
  my $pid = fork();

  if ($pid) {
   push(@childs, $pid);
  }
  elsif ($pid == 0) {
    ... do stuff to $file ...
  }
 }
Run Code Online (Sandbox Code Playgroud)

我不认为这是对的,我希望有人能指出我正确的方向.谢谢.

mob*_*mob 12

除了使用上的麻烦之外fork,您似乎也无法将@files阵列划分为较小的四个文件集.也许是这样的:

for (my $i = 0; $i < @files; $i += 4) {

    # take a slice of 4 elements from @files
    my @files4 = @files[$i .. $i + 3];

    # do something with them in a child process
    if (fork() == 0) {
        ... do something with @files4 ...
        exit;   # <--- this is very important
    }
}

# wait for the child processes to finish
wait for 0 .. @files/4;
Run Code Online (Sandbox Code Playgroud)

  • `使用List :: Gen'by'; 对于我的$ files4(由4 => @files){对@ $ files4做一些事情}` (2认同)

ike*_*ami 5

使用Parallel::ForkManager

use Parallel::ForkManager qw( );

my $pm = Parallel::ForkManager->new(int(@files/4));
for my $file (@files) {
   my $pid = $pm->start and next;

   ... do something with $file ...

   $pm->finish; # Terminates the child process
}
Run Code Online (Sandbox Code Playgroud)

请注意,这仍然会创建 100 个进程,它只是将其限制为 25 个并发。

如果你真的只想要 25 个进程,你可以使用以下方法:

use List::Util            qw( min );
use Parallel::ForkManager qw( );

my $pm = Parallel::ForkManager->new(0+@files);
while (@files) {
   my @batch = @files[0..min(4, $#files)];
   my $pid = $pm->start and next;

   for my $file (@batch) {
      ... do something with $file ...
   }

   $pm->finish; # Terminates the child process
}
Run Code Online (Sandbox Code Playgroud)