加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在php中运行异步功能

发布时间:2020-12-13 17:48:03 所属栏目:PHP教程 来源:网络整理
导读:是否可以创建一些可以异步运行函数的php类?这是我到目前为止所做的: class Worker extends Thread{ protected $asyncFun; protected $paramsArray; public function run() { $asyncFun(/*parameters go here*/) } public function setAsyncFunction($func,
是否可以创建一些可以异步运行函数的php类?这是我到目前为止所做的:

class Worker extends Thread
{
    protected  $asyncFun;
    protected $paramsArray;

    public function run() {
        $asyncFun(/*parameters go here*/)
    }

    public function setAsyncFunction($func,$paramsArr)
    {
        $this->asyncFun = $func;
        $this->paramsArray = $paramsArr;
    }
}

这是我想要的方式:

$worker = new Worker();
$worker->setAsyncFunction(foo,["a","b"]);
$worker::start();

解决方法

最新版本的pthreads支持闭包作为成员,使代码非常简单:

<?php
class Background extends Thread {

    public function __construct(callable $call,array $args = []) {
        $this->call = $call;
        $this->args = $args;
    }

    public function run() {
        call_user_func_array($this->call,$this->args);
    }

    protected $call;
    protected $args;
}

$background = new Background(function($greeting){
    printf("%sn",$greeting);
},["Hello World"]);
$background->start();
$background->join();

function named($greeting) {
    printf("%sn",$greeting);
}

$background = new Background("named",["Goodbye World"]);
$background->start();
$background->join();
?>

然而,这太可怕了,很难想象任何一个如此饥饿的功能需要一个自己的线程.

你已经开始沿着正确的道路开始思考你应该重用上下文并创建一个工作线程,pthreads已经内置了所有这些.

使用内置类的更合理的代码看起来更像:

<?php
class Background extends Threaded {

    public function __construct(callable $call,$this->args);
    }

    protected $call;
    protected $args;
}

$pool = new Pool(4);

$pool->submit(new Background(function($greeting){
    printf("%sn",["Hello World"]));

$pool->shutdown();
?>

但这仍然不涉及返回值.我假设您要检索使用Pool进行的调用的结果,在这种情况下代码看起来更像:

<?php
class Background extends Threaded {

    public function __construct(callable $call,array $args = []) {
        $this->call = $call;
        $this->args = $args;
    }

    public function run() {
        $this->synchronized(function(){
            $this->result = call_user_func_array
                ($this->call,$this->args);
            $this->notify();
        });
    }

    public function getResult() {
        return $this->synchronized(function(){
            while (!isset($this->result))
                $this->wait();
            return $this->result;
        });
    }

    protected $call;
    protected $args;
    protected $result;
}

$pool = new Pool(4);

$call = new Background(function($greeting){
    return sprintf("%sn",["Hello World"]);

$pool->submit($call);

echo $call->getResult();

$pool->shutdown();
?>

正如您所看到的,对Background :: getResult的调用将导致调用上下文一直等到结果可用,这可能是也可能不是,但这是一个很好的例子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读