-
-
Save kefzce/07df26202e2fa1003384b8d1a79d1d80 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 | |
declare(strict_types=1); | |
$loop = new Pool(); | |
$loop->add(function() { | |
echo yield function() { | |
return 1; | |
}; | |
echo yield function() { | |
return 3; | |
}; | |
}); | |
$loop->add(function() { | |
echo yield function() { | |
return 2; | |
}; | |
echo yield function() { | |
return 4; | |
}; | |
}); | |
$loop->run(); |
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 | |
declare(strict_types=1); | |
class Pool | |
{ | |
/** | |
* @var \Generator[]|array[] | |
*/ | |
private $iterators = []; | |
/** | |
* @param Closure $callback | |
* @return Pool | |
*/ | |
public function add(\Closure $callback): Pool | |
{ | |
/** @var \Generator $iterator */ | |
$this->iterators[] = $callback(); | |
return $this; | |
} | |
/** | |
* @return iterable|\Generator[] | |
*/ | |
private function parallel(): iterable | |
{ | |
while (\count($this->iterators)) { | |
foreach ($this->iterators as $i => $iterator) { | |
if (! $iterator->valid()) { | |
unset($this->iterators[$i]); | |
continue; | |
} | |
yield $iterator => $iterator->current(); | |
} | |
} | |
} | |
/** | |
* @return void | |
*/ | |
public function run(): void | |
{ | |
foreach ($this->parallel() as $ctx => $value) { | |
if ($value instanceof \Closure) { | |
$ctx->send($value()); | |
continue; | |
} | |
$ctx->next(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment