我想为这个很棒的社区做点贡献,希望这对某些人有用。尽管 PHP 提供了线程选项和并行运行的多 curl 句柄,但我设法为非线程版本的 PHP 提供了一个解决方案,将每个函数作为其自己的进程运行。
用法: #!/usr/bin/php
用法: php -f /path/to/file
#!/usr/bin/php
<?php
function fork_process($options)
{
$shared_memory_monitor = shmop_open(ftok(__FILE__, chr(0)), "c", 0644, count($options['process']));
$shared_memory_ids = (object) array();
for ($i = 1; $i <= count($options['process']); $i++)
{
$shared_memory_ids->$i = shmop_open(ftok(__FILE__, chr($i)), "c", 0644, $options['size']);
}
for ($i = 1; $i <= count($options['process']); $i++)
{
$pid = pcntl_fork();
if (!$pid)
{
if($i==1)
usleep(100000);
$shared_memory_data = $options['process'][$i - 1]();
shmop_write($shared_memory_ids->$i, $shared_memory_data, 0);
shmop_write($shared_memory_monitor, "1", $i-1);
exit($i);
}
}
while (pcntl_waitpid(0, $status) != -1)
{
if(shmop_read($shared_memory_monitor, 0, count($options['process'])) == str_repeat("1", count($options['process'])))
{
$result = array();
foreach($shared_memory_ids as $key=>$value)
{
$result[$key-1] = shmop_read($shared_memory_ids->$key, 0, $options['size']);
shmop_delete($shared_memory_ids->$key);
}
shmop_delete($shared_memory_monitor);
$options['callback']($result);
}
}
}
$options['size'] = pow(1024,2);
$options['process'][0] = function()
{
sleep(1);
return 'Hello ';
};
$options['process'][1] = function()
{
sleep(1);
return 'World!';
};
$options['callback'] = function($result)
{
echo $result[0].$result[1]."\n";
};
fork_process($options);
?>
如果您想从网页获取结果,请使用 exec()。例如:echo exec('php -f /path/to/file');
继续 hacking!:)