简体   繁体   English

从PHP并行执行脚本并等待

[英]Parallel script execution from PHP and waiting

I have to start many scripts from PHP and finish them as fast as possible. 我必须从PHP启动许多脚本并尽快完成它们。 These scripts are written in a different language, though. 但是,这些脚本是用不同的语言编写的。 I've started them somehow but I don't know how to wait for them. 我已经以某种方式启动了它们,但是我不知道如何等待它们。 My code: 我的代码:

foreach ($commands as $command) {
    exec($command.' &');
}

The PHP script stop execution but there is still a lot of work in the background. PHP脚本停止执行,但后台仍有大量工作。 How to wait in PHP for these tasks? 如何在PHP中等待这些任务?

Similar questions: 类似问题:
Parallel processing in PHP - How do you do it? PHP中的并行处理-如何做到? – waiting/synchronisation ignored –等待/同步被忽略
Executing multiple PHP scripts in parallel, and being notified when finished – limited to PHP scripts 并行执行多个PHP脚本,并在完成时收到通知 -仅限PHP脚本

If the scripts to execute are written in different languages, the best approach is probably GNU parallel : 如果要执行的脚本是用不同的语言编写的,则最好的方法可能是GNU parallel

Note the documentation: 请注意文档:

If command is given, GNU parallel solve the same tasks as xargs. 如果给出命令,GNU parallel将解决与xargs相同的任务。 If command is not given GNU parallel will behave similar to cat | 如果未给出命令,则GNU parallel的行为类似于cat | sh. sh。

So you can easily build, in PHP, a list of task to do separated by newlines, and feed them to parallel like this: 因此,您可以轻松地在PHP中构建要用换行符分隔的任务列表,并将其馈送给parallel如下所示:

echo $'ls\necho 42\npython3 -c "print(43)"' | parallel 
1
2
3
42
43

Feeding the list of tasks to parallel 's stdin is not that hard using proc_open in PHP. 在PHP中使用proc_open将任务列表馈送parallelstdin并不难。

Then you'll just have to wait for parallel to complete, when parallel has terminated, all subtasks are terminated too, and you can easily configure how many tasks are executed in parallel, if you have too many, executing them all in parallel like you're trying to do will be slower than starting them 5 by 5 like parallel can typically do. 然后,您只需要等待并行操作完成,当并行操作终止时,所有子任务也将终止,并且您可以轻松配置并行执行的任务数量(如果太多),像您一样并行执行所有任务尝试做起来比parallel通常以5开头5的速度要慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM