Created
August 30, 2022 08:28
-
-
Save bartvanhoutte/6f39d78cc89f0cc2e3fb174cec276e2d to your computer and use it in GitHub Desktop.
Fibers
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 Loop | |
{ | |
private static ?Loop $loop = null; | |
private array $queue = []; | |
private bool $running = false; | |
private static function get(): self | |
{ | |
if (self::$loop === null) { | |
self::$loop = new static; | |
} | |
return self::$loop; | |
} | |
public static function futureTick(callable $callable): void | |
{ | |
Loop::get()->queue[] = new Fiber($callable); | |
} | |
public static function run(): void | |
{ | |
$loop = Loop::get(); | |
$loop->running = true; | |
while ($loop->running) { | |
if ($loop->queue !== []) { | |
$fiber = array_shift($loop->queue); | |
if (!$fiber->isStarted()) { | |
$fiber->start(); | |
$loop->queue[] = $fiber; | |
} elseif ($fiber->isSuspended()) { | |
$fiber->resume(); | |
$loop->queue[] = $fiber; | |
} | |
} | |
if ($loop->queue === []) { | |
$loop->running = false; | |
} | |
} | |
} | |
} | |
register_shutdown_function(Loop::run(...)); | |
Loop::futureTick(fn() => print date('c') . ' - tick' . PHP_EOL); | |
Loop::futureTick(function () { | |
print date('c') . ' - fiber 1' . PHP_EOL; | |
Fiber::suspend(); | |
print date('c') . ' - fiber 1' . PHP_EOL; | |
}); | |
Loop::futureTick(fn() => print date('c') . ' - tock' . PHP_EOL); | |
Loop::futureTick(static function () { | |
print date('c') . ' - going to sleep' . PHP_EOL; | |
Fiber::suspend(); | |
print date('c') . ' - zug zug' . PHP_EOL; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment