-
-
Save trowski/ac90817f7000e0ae7bab41320e224172 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 | |
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