【问题标题】:paralle::forkmanager perl module并行::forkmanager perl 模块
【发布时间】:2014-06-06 10:44:37
【问题描述】:

我有一个大约 10000 个数据的大数组,想用 parallel::forkmanager 处理它

如何处理 1000 块的数据我有以下代码:

my $MAX_PROCESSES = 10;

 my  $pm = new Parallel::ForkManager($MAX_PROCESSES);

    for (<>) {
       my $pid = $pm->start and next; 
      #  here i want to process my data on chunks of 1000 with 10 parallel::formanagaer
       $pm->finish; 
         }

如何自定义我的代码来做到这一点?

【问题讨论】:

    标签: perl cpan


    【解决方案1】:

    正如文档所示,数据是从父级传递给子级的,因此您需要采用以下形式的内容:

    for (;;) {
       ... get a chunk ...
       my $pid = $pm->start and next; 
       ... process chunk ...
       $pm->finish; 
    }
    

    所以

    use constant CHUNK_SIZE => 1000;
    
    CHUNK:    
    for (my $eof = 0; !$eof;) {
       my @chunk;
       while (@chunk < CHUNK_SIZE) {
          my $line = <>;
          if (!$line) {
             if (@chunk) {
                $eof = 1;  # Can't rely on a handle returning EOF twice.
                last;      #   so we have to make a note of it.
             } else {
                last CHUNK;
             }
          }
    
          push @chunk, $line;
       }
    
       my $pid = $pm->start and next; 
       ... process chunk ...
       $pm->finish; 
    }
    

    【讨论】:

      【解决方案2】:
      my $max_procs = 4;
      my $pm = new Parallel::ForkManager($max_procs);
      
      foreach my $index ( 0 .. $max_procs-1 ) {
          my $cmd = $$cli_to_execute[$index];
      
          # Forks and returns the pid for the child:
          my $pid = $pm->start($index) and next;
      
          my $out = &cli_command( $cmd ) unless $pid; ### This code is the child process
      
          $pm->finish($index, \$out); # pass an exit code to finish
      }
      
      print "Waiting for children...\n";
      $pm->wait_all_children;
      

      【讨论】:

      • 不要只发布一段代码作为答案。请花时间解释您的代码是如何工作的和/或为什么原始代码不能。
      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多