当前位置: 移动技术网 > IT编程>开发语言>PHP > php基于协程实现异步的方法分析

php基于协程实现异步的方法分析

2019年09月06日  | 移动技术网IT编程  | 我要评论

本文实例讲述了php基于协程实现异步的方法。分享给大家供大家参考,具体如下:

github上php的协程大部分是根据这篇文章实现的:http://nikic.github.io/2012/12/22/cooperative-multitasking-using-coroutines-in-php.html

它们最终的结果都是把回调变成了优雅的顺序执行的代码,但还是阻塞的,不是真正的异步。

比如最热门的:https://github.com/recoilphp/recoil

先安装:

composer require recoil/recoil

执行:

<?php
//recoil.php
include __dir__ . '/vendor/autoload.php';
use recoil\react\reactkernel;
$i = 100000;
reactkernel::start(task1());
reactkernel::start(task2());
function task1(){
  global $i;
  echo "wait start" . php_eol;
  while ($i-- > 0) {
    yield;
  }
  echo "wait end" . php_eol;
};
function task2(){
  echo "hello " . php_eol;
  yield;
  echo "world!" . php_eol;
}

结果:

wait start
//等待若干秒
wait end
hello
world!

我本来是想让两个任务并行,结果两个任务变成了串行,中间等待的时间什么事情都干不了。react响应式的编程是严格禁止这种等待的,所以我就参照unity3d的协程自己写了个php版本的。上代码:

<?php
//coroutine.php
//依赖swoole实现的定时器,也可以用其它方法实现定时器
class coroutine
{
  //可以根据需要更改定时器间隔,单位ms
  const tick_interval = 1;
  private $routinelist;
  private $tickid = -1;
  public function __construct()
  {
    $this->routinelist = [];
  }
  public function start(generator $routine)
  {
    $task = new task($routine);
    $this->routinelist[] = $task;
    $this->starttick();
  }
  public function stop(generator $routine)
  {
    foreach ($this->routinelist as $k => $task) {
      if($task->getroutine() == $routine){
        unset($this->routinelist[$k]);
      }
    }
  }
  private function starttick()
  {
    swoole_timer_tick(self::tick_interval, function($timerid){
      $this->tickid = $timerid;
      $this->run();
    });
  }
  private function stoptick()
  {
    if($this->tickid >= 0) {
      swoole_timer_clear($this->tickid);
    }
  }
  private function run()
  {
    if(empty($this->routinelist)){
      $this->stoptick();
      return;
    }
    foreach ($this->routinelist as $k => $task) {
      $task->run();
      if($task->isfinished()){
        unset($this->routinelist[$k]);
      }
    }
  }
  
}
class task
{
  protected $stack;
  protected $routine;
  public function __construct(generator $routine)
  {
    $this->routine = $routine;
    $this->stack = new splstack();
  }
  /**
   * [run 协程调度]
   * @return [type]     [description]
   */
  public function run()
  {
    $routine = &$this->routine;
    try {
      if(!$routine){
        return;
      }
      $value = $routine->current();
      //嵌套的协程
      if ($value instanceof generator) {
        $this->stack->push($routine);
        $routine = $value;
        return;
      }
      //嵌套的协程返回
      if(!$routine->valid() && !$this->stack->isempty()) {
        $routine = $this->stack->pop();
      }
      $routine->next();
    } catch (exception $e) {
      if ($this->stack->isempty()) {
        /*
          throw the exception
        */
        return;
      }
    }
  }
  /**
   * [isfinished 判断该task是否完成]
   * @return boolean [description]
   */
  public function isfinished()
  {
    return $this->stack->isempty() && !$this->routine->valid();
  }
  public function getroutine()
  {
    return $this->routine;
  }
}

测试代码:

<?php
//test.php
 require 'coroutine.php';
$i = 10000;
$c = new coroutine();
$c->start(task1());
$c->start(task2());
function task1(){
  global $i;
  echo "wait start" . php_eol;
  while ($i-- > 0) {
    yield;
  }
  echo "wait end" . php_eol;
};
function task2(){
  echo "hello " . php_eol;
  yield;
  echo "world!" . php_eol;
}

结果:

wait start
hello
world!
//等待几秒,但不阻塞
wait end

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网