php中实现异步功能,在php中运行异步功能

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

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("%s\n", $greeting);

}, ["Hello World"]);

$background->start();

$background->join();

function named($greeting) {

printf("%s\n", $greeting);

}

$background = new Background("named", ["Goodbye World"]);

$background->start();

$background->join();

?>

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

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

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

class Background extends Threaded {

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;

}

$pool = new Pool(4);

$pool->submit(new Background(function($greeting){

printf("%s\n", $greeting);

}, ["Hello World"]));

$pool->shutdown();

?>

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

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("%s\n", $greeting);

}, ["Hello World"]);

$pool->submit($call);

echo $call->getResult();

$pool->shutdown();

?>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值