Timers and a repeating callback
<?php use Fledge\Loop; Loop::defer(function () { echo "deferred\n";}); Loop::delay(0.12, function () { echo "after 120 ms\n";}); $n = 0;Loop::repeat(0.05, function (string $id) use (&$n) { echo 'tick ', ++$n, "\n"; if ($n === 3) { Loop::cancel($id); }}); Loop::run();
Prints deferred, tick 1, tick 2, after 120 ms, tick 3.
Read from a stream
<?php use Fledge\Loop; [$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);stream_set_blocking($reader, false); Loop::onReadable($reader, function (string $id, $stream) { echo 'got: ', fread($stream, 1024), "\n"; Loop::cancel($id); // cancel before you close fclose($stream);}); Loop::delay(0.05, function () use ($writer) { fwrite($writer, 'hello');}); Loop::run();
Prints got: hello.
Await pattern with suspensions
Two fibers wait on their own suspensions at the same time. Both results arrive after about 50 ms, not 100 ms, because the loop keeps running while each fiber is parked.
<?php use Fledge\Loop; function fetch(string $what): string{ $suspension = Loop::getSuspension(); Loop::delay(0.05, fn () => $suspension->resume("result of $what")); return $suspension->suspend();} Loop::queue(function () { echo fetch('A'), "\n";});Loop::queue(function () { echo fetch('B'), "\n";}); Loop::run();
Prints result of A and result of B.
Handle a signal
Requires ext-pcntl; the example also uses posix_kill() from ext-posix.
<?php use Fledge\Loop; Loop::onSignal(SIGUSR1, function (string $id) { echo "got SIGUSR1\n"; Loop::cancel($id); // the last callback gone: the default disposition is back}); Loop::delay(0.05, function () { posix_kill(getmypid(), SIGUSR1);}); Loop::run();
A signal callback is installed with the kernel at the loop tick after onSignal() returns, not at once. Cancelling the last callback for a signal restores its default disposition.
Fork a worker from a master
Requires ext-pcntl. Fork from {main}, never from a loop callback or a fiber: a master that decides to fork inside the loop suspends {main} and forks once it has resumed. Loop::fork() is pcntl_fork() plus Loop::afterFork() in the child, so the child starts on a fresh, empty loop.
<?php $workers = 0;while ($workers < $wanted) { $suspension = Fledge\Loop::getSuspension(); Fledge\Loop::delay(0.5, $suspension->resume(...)); // or resume from a signal, timer or socket callback $suspension->suspend(); // back in {main} here if (Fledge\Loop::fork() === 0) { runWorker(); exit(0); } $workers++;}
$wanted and runWorker() are yours. If you call pcntl_fork() yourself, call Fledge\Loop::afterFork() first thing in the child.
<?php $pid = pcntl_fork();if ($pid === 0) { Fledge\Loop::afterFork(); // first thing in the child, from {main}}
Pick the driver in code
<?php Fledge\Loop::install('poll'); echo Fledge\Loop::driverName(), "\n"; // poll
Call install() before the loop has run anything. Loop::hasDriver() and Loop::driverName() report the driver without creating one.