Last active
January 13, 2021 20:16
-
-
Save SerafimArts/b89f02039c2ba61dcfde04d3fdfe7d52 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 hidden or 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