2013-07-22 32 views
0
$a=new FileProcessing($path1); 
$b=new FileProcessing($path2); 
$a->doProcessFile(); 
$b->doProcessFile(); 

此代碼運行doProcessFile()$a然後在順序運行doProcessFile()$b。 我要爲$a平行doProcessFile()$b,所以我可以在parralel處理不同的文件運行doProcessFile()。 我可以在PHP中做到這一點?PHP平行類實例

正如我所看到的,PHP處理腳本只能按順序排列。現在我想知道是否可以在parralel中運行同一腳本的多個實例,運行腳本之間的區別是我在調用每個腳本時傳遞的參數。例如:php myscript.php [path1]然後我用不同的參數第二次調用這個腳本。

+4

編號PHP不是多線程語言。你唯一的辦法就是'exec()'或者其他的產生php的兩個SEPARATE實例,每個實例都有自己獨立的路徑。 –

+1

http://stackoverflow.com/questions/14236296/asynchronous-function-call-in-php – castis

+0

就像@MarcB提到的PHP不是多線程的。除了使用exec,你也可以看看像beanstalkD的解決方案http://kr.github.io/beanstalkd/ – tlenss

回答

0

您可以使用pcntl_fork,但只能從命令行運行PHP而不是Web服務器。

或者,您可以使用gearman

0

從未嘗試過自己,但在理論上應該是可能的:

  1. 將您doProcessingFile方法爲獨立的PHP腳本process_file.php這需要要處理的文件作爲輸入。

  2. 把文件進行處理,從而爲唯一目的

  3. 創建一個shell腳本paralellizer,將列出文件夾與文件處理和發送文件進行並行處理創建的文件夾(注意,它接受數 - 要處理的文件作爲arg的這一點也許可以被如下oneliner的一部分)進行更好:

    #!/bin/bash 
    
    ls special_folder | xargs -P $1 -n 1 php process_file.php 
    
  4. 呼叫parallelizer從PHP,並確保process_file退貨處理結果狀態:

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

免責聲明:只是理念的粗糙難看草圖。我敢肯定,這可以改善

0

使2檔

1. processor.php

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

2. caller.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環境