$a=new FileProcessing($path1);
$b=new FileProcessing($path2);
$a->doProcessFile();
$b->doProcessFile();
此代码为doProcessFile()
运行$a
,然后在连续顺序中为doProcessFile()
运行$b
。
我希望doProcessFile()
在并行中$a
与doProcessFile()
$b
一起运行,因此我可以在 parralel 中处理不同的文件。
我可以用PHP做到这一点吗?
正如我所看到的,PHP进程脚本只按顺序排列。现在我想知道我是否可以在parralel中运行相同脚本的多个实例,运行脚本之间的区别是我调用每个脚本时传递的参数。例如:php myscript.php [path1]
然后我用不同的参数第二次调用这个脚本。
答案 0 :(得分:0)
您可以使用pcntl_fork
,但仅限于从命令行而不是作为Web服务器运行PHP时。
或者,您可以使用gearman。
答案 1 :(得分:0)
从来没有尝试过,但理论上应该是可能的:
将doProcessingFile
方法转换为独立的PHP脚本process_file.php
,将文件作为输入进行处理。
将要处理的文件放入为此唯一目的创建的文件夹
创建一个shell脚本paralellizer
,它将列出包含要处理的文件的文件夹并发送文件以进行并行处理(请注意,它接受要处理的文件数量为arg - 这个位可以完成作为下面的oneliner的一部分更好):
#!/bin/bash
ls special_folder | xargs -P $1 -n 1 php process_file.php
从php调用parallelizer
并确保process_file返回处理结果状态:
$files_to_process = Array($path1, $path2);
exec('parallelizer '.count($files_to_process), $output);
// check output
// access processed files
答案 2 :(得分: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环境