Skip to content

Instantly share code, notes, and snippets.

@trowski
Last active November 26, 2020 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trowski/ac90817f7000e0ae7bab41320e224172 to your computer and use it in GitHub Desktop.
Save trowski/ac90817f7000e0ae7bab41320e224172 to your computer and use it in GitHub Desktop.
<?php
class Scheduler implements FiberScheduler
{
private string $nextId = 'a';
private array $callbacks = [];
public function run(): void
{
while (!empty($this->callbacks)) {
foreach ($this->callbacks as $id => $callback) {
unset($this->callbacks[$id]);
$callback();
}
}
}
public function defer(callable $callback): void
{
$this->callbacks[$this->nextId++] = $callback;
}
}
$scheduler = new Scheduler;
// Pause main fiber, which will be resumed by the scheduler.
$value = \Fiber::suspend(fn(Fiber $fiber) => $scheduler->defer(fn() => $fiber->resume("Test")), $scheduler);
echo "After resuming main fiber: ", $value, "\n";
// Pause main fiber again, but this time an exception will be thrown.
\Fiber::suspend(fn(Fiber $fiber) => $scheduler->defer(fn() => $fiber->throw(new Exception("Test"))), $scheduler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment