【问题标题】:PHP run parallel class instancesPHP 运行并行类实例
【发布时间】:2013-07-22 21:03:17
【问题描述】:
$a=new FileProcessing($path1);
$b=new FileProcessing($path2); 
$a->doProcessFile();
$b->doProcessFile();

此代码运行doProcessFile() for $a 然后运行doProcessFile() for $b顺序。 我想在 parallel 中运行 doProcessFile() for $adoProcessFile() for $b,这样我就可以在 parralel 中处理不同的文件。 我可以在 PHP 中做到这一点吗?

如我所见,PHP 仅按顺序处理脚本。现在我想知道我是否可以在 parralel 中运行同一脚本的多个实例,运行脚本之间的区别是我在调用每个脚本时传递的参数。例如:php myscript.php [path1] 然后我用不同的参数第二次调用这个脚本。

【问题讨论】:

  • 没有。 PHP 不是多线程语言。您唯一的办法是exec() 或以其他方式生成两个单独的 php 实例,每个实例都有各自的路径。
  • 就像@MarcB 提到的 PHP 不是多线程的。除了使用 exec 您还可以查看 beanstalkD kr.github.io/beanstalkd 之类的解决方案
  • @tlens - php 不是多线程的? www.php.net/Thread 不同意你的观点:/
  • @N.B.pthreads 不是核心的一部分。所以答案依然存在。然而,这是一个可行的选择。

标签: php


【解决方案1】:

您可以使用pcntl_fork,但只能在从命令行而不是作为 Web 服务器运行 PHP 时使用。

或者,您可以使用gearman

【讨论】:

    【解决方案2】:

    制作 2 个文件

    1。处理器.php

    <?php
    if($arc < 1) user_error('needs a argument');
    $a=new FileProcessing($argv[1]);
    $a->doProcessFile();
    

    2。调用者.php

    <?php
    function process($path,$name){
      $a = array();
      $descriptorspec = array(
        1 => array("file", "/tmp/$name-output.txt", "a"),  // stdout is a pipe that the child will write to
        2 => array("file", "/tmp/$name-error.txt", "a") // stderr is a file to write to
      );
      return proc_open(PHP_BINARY.' processor.php '.escapeshellarg($path), $descriptorspec, $a);
    }
    $proc1 = process($path1,'path1');
    $proc2 = process($path2,'path2');
    //now wait for them to complete
    if(proc_close($proc1))user_error('proc1 returned non 0');
    if(proc_close($proc2))user_error('proc2 returned non 0');
    echo 'All done!!';
    

    请务必阅读proc_open 的文档以了解更多信息,还请注意,您需要在处理器中包含类(以及它需要的任何东西),因为它是一个新的 php 环境

    【讨论】:

      【解决方案3】:

      我自己从未尝试过,但理论上应该是可能的:

      1. 将您的 doProcessingFile 方法转换为一个独立的 PHP 脚本 process_file.php,它将文件作为输入进行处理。

      2. 将要处理的文件放入专门为此目的创建的文件夹中

      3. 创建一个 shell 脚本paralellizer,它将列出包含要处理的文件的文件夹并发送文件以进行并行处理(请注意,它接受要处理的文件数量作为 arg - 这个位可能作为下面的单线):

         #!/bin/bash
        
         ls special_folder | xargs -P $1 -n 1 php process_file.php
        
      4. 从 php 调用 parallelizer 并确保 process_file 返回处理结果状态:

         $files_to_process = Array($path1, $path2); 
         exec('parallelizer '.count($files_to_process), $output);
         // check output
         // access processed files  
        

      免责声明:只是一个粗略的丑陋草图。我相信它可以改进

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-18
        • 2022-01-23
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 2014-12-16
        相关资源
        最近更新 更多