在PHP中并行执行功能 [英] Executing functions parallelly in PHP
问题描述
PHP可以调用一个函数,而不必等待它返回吗?所以像这样:
Can PHP call a function and don't wait for it to return? So something like this:
function callback($pause, $arg) {
sleep($pause);
echo $arg, "\n";
}
header('Content-Type: text/plain');
fast_call_user_func_array('callback', array(3, 'three'));
fast_call_user_func_array('callback', array(2, 'two'));
fast_call_user_func_array('callback', array(1, 'one'));
将输出
one (after 1 second)
two (after 2 seconds)
three (after 3 seconds)
而不是
three (after 3 seconds)
two (after 3 + 2 = 5 seconds)
one (after 3 + 2 + 1 = 6 seconds)
主脚本旨在作为永久进程(TCP服务器)运行. callback()
函数将从客户端接收数据,执行外部PHP脚本,然后根据传递给callback()
的其他参数进行操作.问题在于主脚本不得等待外部PHP脚本完成.外部脚本的结果很重要,因此exec('php -f file.php &')
不是一个选择.
Main script is intended to be run as a permanent process (TCP server). callback()
function would receive data from client, execute external PHP script and then do something based on other arguments that are passed to callback()
. The problem is that main script must not wait for external PHP script to finish. Result of external script is important, so exec('php -f file.php &')
is not an option.
许多人建议您看一下PCNTL,因此似乎可以实现这种功能. PCNTL在Windows中不可用,并且我现在无法访问Linux机器,因此我无法对其进行测试,但是如果有很多人建议,那么它应该可以解决这个问题:)
Many have recommended to take a look at PCNTL, so it seems that such functionality can be achieved. PCNTL is not available in Windows, and I don't have an access to a Linux machine right now, so I can't test it, but if so many people have advised it, then it should do the trick :)
谢谢大家!
推荐答案
On Unix platforms you can enable the PCNTL functions, and use pcntl_fork
to fork the process and run your jobs in child processes.
类似的东西:
function fast_call_user_func_array($func, $args) {
if (pcntl_fork() == 0) {
call_user_func_array($func, $args);
}
}
一旦调用pcntl_fork
,两个进程将从同一位置执行您的代码.父进程将获得pcntl_fork
返回的PID,而子进程将获得0
. (如果发生错误,父进程将返回-1
,值得在生产代码中进行检查.)
Once you call pcntl_fork
, two processes will execute your code from the same position. The parent process will get a PID returned from pcntl_fork
, while the child process will get 0
. (If there's an error the parent process will return -1
, which is worth checking for in production code).
这篇关于在PHP中并行执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!