在后台线程/进程中调用函数(forking)


Calling a function in a background thread / process (forking)

我的代码有点像这样:

($i=0; $i < 100; $i++)
{
   do ($foo[$i]);
}

以上是一项耗时的任务,我希望能够创建一个函数,并像下面的一样调用它两次

function wrapper($start;$end)
{
    ($i=$start; $i < $end; $i++)
    {
       do ($foo[$i]);
    }
}
//have both of these run in parallel
wrapper(0,50);
wrapper(51,100);

我看了Gearman,但我不能使用它,因为我不能安装Gearman服务器(因为我在共享服务器上)。实现这一目标的方法似乎是分叉。我试着读了很多关于它的内容,但文档和支持都很少。任何帮助/线框代码都将不胜感激。

为了定义我的问题,我如何调用传递参数的wrapper(),使其在子进程中执行。此外,我能够注册回调函数也是很重要的。

附加细节:PHP 5.3,运行在Linux服务器上。脚本由cgi-fcgi执行。

我认为这就是我应该如何生成一个子进程,但我如何使用它来生成多个子进程?如何注册回调函数?

$pid = pcntl_fork(); 
if ( $pid == -1 ) {        
    // Fork failed            
    exit(1); 
} else if ( $pid ) { 
    // The parent process
    //should I repeat this same code here to spawn another child process?
} else { 
    // the child process 
    //can I call wrapper from here and will it run in this child process?

来自"Tudor Barbu的专业博客"
(http://blog.motane.lu/2009/01/02/multithreading-in-php/)

require_once( 'Thread.php' );
// test to see if threading is available
if( ! Thread::isAvailable() ) {
    die( 'Threads not supported' );
}
// function to be ran on separate threads
function paralel( $_limit, $_name ) {
    for ( $index = 0; $index < $_limit; $index++ ) {
        echo 'Now running thread ' . $_name . PHP_EOL;
        sleep( 1 );
    }
}
// create 2 thread objects
$t1 = new Thread( 'paralel' );
$t2 = new Thread( 'paralel' );
// start them
$t1->start( 10, 't1' );
$t2->start( 10, 't2' );
// keep the program running until the threads finish
while( $t1->isAlive() && $t2->isAlive() ) {
}

下载Thread.php

如果您使用的是Linux,您可以利用命令行执行

public function newWrapperInstance($start,$end){
    exec('bash -c "exec nohup setsid php-cli yourFile.php '.$start.' '.$end.' > /dev/null 2>&1 &"');
}

这将在后台创建一个新的PHP实例,并将其与主线程中的exec函数分离。

警告:唯一的缺点是,一旦创建了这些线程,就无法控制它们的操作。