并行执行功能 [英] Executing functions in parallel
问题描述
我有一个函数,该函数需要遍历数组中的约20K行,并对每个行应用一个外部脚本.这是一个缓慢的过程,因为PHP在继续下一行之前正在等待脚本执行.
I have a function that needs to go over around 20K rows from an array, and apply an external script to each. This is a slow process, as PHP is waiting for the script to be executed before continuing with the next row.
为了使此过程更快,我正在考虑同时在不同部分中运行该功能.因此,例如,将行0到2000作为一个函数,将行2001到4000作为另一个函数,依此类推.我该如何整齐地做到这一点?我可以进行不同的cron作业,每个函数使用不同的参数:myFunction(0, 2000)
,然后使用myFunction(2001, 4000)
进行另一个cron作业,等等,但这似乎不太干净.这样做有什么好方法?
In order to make this process faster I was thinking on running the function in different parts, at the same time. So, for example, rows 0 to 2000 as one function, 2001 to 4000 on another one, and so on. How can I do this in a neat way? I could make different cron jobs, one for each function with different params: myFunction(0, 2000)
, then another cron job with myFunction(2001, 4000)
, etc. but that doesn't seem too clean. What's a good way of doing this?
推荐答案
如果您想在PHP中执行并行任务,我会考虑使用 pcntl_fork(),但是我更喜欢基于任务的实际工人.
If you'd like to execute parallel tasks in PHP, I would consider using Gearman. Another approach would be to use pcntl_fork(), but I'd prefer actual workers when it's task based.
这篇关于并行执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!