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

xbo*_*nez 18 php parallel-processing fork

我的代码有点像这样:

($i=0; $i < 100; $i++)
{
   do ($foo[$i]);
}
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

我看着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?
Run Code Online (Sandbox Code Playgroud)

Bee*_*eel 12

来自"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() ) {

}
Run Code Online (Sandbox Code Playgroud)

下载Thread.php