在后台线程/进程中调用函数(派生) [英] Calling a function in a background thread / process (forking)

查看:76
本文介绍了在后台线程/进程中调用函数(派生)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有点像这样:

($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?

推荐答案

来自"都铎·巴布的专业博客"
(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() ) {

}

Download Thread.php

这篇关于在后台线程/进程中调用函数(派生)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆