Skip to content

Instantly share code, notes, and snippets.

@SerafimArts
Last active January 13, 2021 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SerafimArts/b89f02039c2ba61dcfde04d3fdfe7d52 to your computer and use it in GitHub Desktop.
Save SerafimArts/b89f02039c2ba61dcfde04d3fdfe7d52 to your computer and use it in GitHub Desktop.
<?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();
<?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