Last active
January 1, 2016 06:19
-
-
Save dadamssg/8104340 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$obj = new \stdClass; | |
$obj->x = ''; | |
$gen1 = function() use ($obj) { | |
$obj->x .= ' 1 '; | |
yield; | |
$obj->x .= ' 2 '; | |
yield; | |
$obj->x .= ' 3 '; | |
yield; | |
$obj->x .= ' 4 '; | |
}; | |
$gen2 = function() use ($obj) { | |
$obj->x .= ' A '; | |
yield; | |
$obj->x .= ' B '; | |
yield; | |
$obj->x .= ' C '; | |
yield; | |
$obj->x .= ' D '; | |
}; | |
$master = new TaskMaster; | |
$master->queue($gen1()); | |
$master->queue($gen2()); | |
$master->run(); | |
echo trim($obj->x); // '1 A 2 B 3 C 4 D' | |
class TaskMaster | |
{ | |
protected $tasks = []; | |
public function queue(\Generator $generator) | |
{ | |
$task = new Task($generator); | |
$this->schedule($task); | |
} | |
public function schedule(Task $task) | |
{ | |
$this->tasks[] = $task; | |
} | |
public function run() | |
{ | |
while (count($this->tasks)) { | |
$task = array_shift($this->tasks); | |
$task->run(); | |
if ( ! $task->isDone()) { | |
$this->schedule($task); | |
} | |
} | |
} | |
} | |
class Task | |
{ | |
protected $generator; | |
protected $initiated = false; | |
protected $sendValue; | |
public function __construct(\Generator $generator) | |
{ | |
$this->generator = $generator; | |
} | |
public function setSendValue($value) | |
{ | |
$this->sendValue = $value; | |
} | |
public function run() | |
{ | |
if ( ! $this->initiated) { | |
$this->initiated = true; | |
return $this->generator->current(); | |
} | |
return $this->generator->send($this->sendValue); | |
} | |
public function isDone() | |
{ | |
return ! $this->generator->valid(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment