Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Perl中使用fork()?_Perl_Fork - Fatal编程技术网

如何在Perl中使用fork()?

如何在Perl中使用fork()?,perl,fork,Perl,Fork,我在一个数组中有数百个文件名。我想为数组中的每4个文件创建一个子进程,并让该子进程对这4个文件中的每个文件执行一些操作。(因此,对于100个文件,我将创建25个进程。) 当有叉子时,我很难理解行的处理顺序。我想我可以做这样的事情,但我被卡住了: foreach $file (@files) { if ($f++ % 4 == 0) { my $pid = fork(); if ($pid) { push(@childs, $pid); } elsif ($pid ==

我在一个数组中有数百个文件名。我想为数组中的每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 ...
  }
 }

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

除了在使用
fork
时遇到问题外,您似乎还无法将
@文件
数组划分为四个较小的文件集。也许是这样的:

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;
用于(我的$i=0;$i<@文件;$i+=4){
#从@files中获取4个元素的片段
my@files4=@files[$i..$i+3];
#在子进程中对它们执行一些操作
如果(fork()==0){
…对@files4执行某些操作。。。

exit;#我将分组到一个数组,并让子进程处理该组

my $group = []
foreach my $file (@files) {
    push @$group, $file;

    if(scalar(@$group) % 4 == 0) {
        my $pid = fork;
        die "Unable to fork!" unless defined $pid;
        push @childs, $pid if $pid;
        children_work($group) unless $pid;
        $group = [];
    }        
}

sub children_work {
   my $group = shift;

   // child, work with $group
   exit(0);
}
使用

请注意,这仍然会创建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
}

while(my@files4=splice(@files,0,4)){
(尽管会销毁@files),因为您将
$i
增加4,所以在切片时不需要将其乘以4,对吗?
使用List::Gen'by';对于my$files4(by 4=>@files){对@code$files4做点什么}
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
}