本文实例讲述了php实现简单的协程任务调度。分享给大家供大家参考,具体如下:

<?php
class task
{
  protected $taskid;
  protected $coroutine;
  protected $sendvalue = null;
  protected $beforefirstyield = true;
  public function __construct($taskid, generator $coroutine)
  {
    $this->taskid = $taskid;
    $this->coroutine = $coroutine;
  }
  public function gettaskid()
  {
    return $this->taskid;
  }
  public function setsendvalue($sendvalue)
  {
    $this->sendvalue = $sendvalue;
  }
  public function run()
  {
    if ($this->beforefirstyield) {
      $this->beforefirstyield = false;
      return $this->coroutine->current();
    } else {
      $retval = $this->coroutine->send($this->sendvalue);
      $this->sendvalue = null;
      return $retval;
    }
  }
  public function isfinished()
  {
    return !$this->coroutine->valid();
  }
}
class scheduler
{
  protected $maxtaskid = 0;
  protected $taskmap = []; // taskid => task
  protected $taskqueue;
  public function __construct()
  {
    $this->taskqueue = new splqueue();
  }
  public function newtask(generator $coroutine)
  {
    $tid = ++$this->maxtaskid;
    $task = new task($tid, $coroutine);
    $this->taskmap[$tid] = $task;
    $this->schedule($task);
    return $tid;
  }
  public function schedule(task $task)
  {
    $this->taskqueue->enqueue($task);
  }
  public function run()
  {
    while (!$this->taskqueue->isempty()) {
      $task = $this->taskqueue->dequeue();
      $task->run();
      if ($task->isfinished()) {
        unset($this->taskmap[$task->gettaskid()]);
      } else {
        $this->schedule($task);
      }
    }
  }
}
function task1()
{
  for ($i = 1; $i <= 10; ++$i) {
    echo "this is task 1 iteration $i.\n";
    sleep(1);
    yield;
  }
}
function task2()
{
  for ($i = 1; $i <= 10; ++$i) {
    echo "this is task 2 iteration $i.\n";
    sleep(1);
    yield;
  }
}
$scheduler = new scheduler;
$scheduler->newtask(task1());
$scheduler->newtask(task2());
$scheduler->run();

运行结果:

this is task 1 iteration 1.
this is task 1 iteration 2.
this is task 1 iteration 3.
this is task 1 iteration 4.
this is task 1 iteration 5.
this is task 1 iteration 6.
this is task 1 iteration 7.
this is task 1 iteration 8.
this is task 1 iteration 9.
this is task 1 iteration 10.