Cancellation and cleanup
Examples
Every example of this topic, with its output.
phasync::finally#
phasync::run(function () {
phasync::go(function () {
phasync::finally(fn () => print("registered first\n"));
phasync::finally(fn () => print("registered second\n")); // prints first
phasync::sleep(0.1);
});
});phasync::cancel#
phasync::run(function () {
$worker = phasync::go(function () {
try {
while (true) {
phasync::sleep(1);
}
} finally {
echo "cleaned up\n";
}
});
phasync::sleep(0.1);
phasync::cancel($worker);
try {
phasync::await($worker);
} catch (phasync\CancelledException) {
echo "cancelled\n";
}
});phasync::throw#
phasync::run(function () {
$fiber = phasync::go(function () {
try {
phasync::sleep(10);
} catch (RuntimeException $e) {
echo "interrupted: ", $e->getMessage(), "\n";
}
phasync::sleep(0.01); // an ordinary wait again
return 'carried on';
});
phasync::throw($fiber, new RuntimeException('wake up'));
echo phasync::await($fiber), "\n";
});phasync::signal#
phasync::go(function () use ($server) {
phasync::signal([SIGTERM, SIGINT]);
$server->close(); // stop accepting, let the requests in flight finish
});phasync::onSignal#
phasync::onSignal(SIGQUIT, function () {
error_log('stuck at ' . (new Exception())->getTraceAsString());
});phasync::shutdown#
phasync::go(function () {
phasync::signal(SIGTERM);
if (phasync::shutdown(2.0) > 0) {
exit(1); // some coroutines didn't stop in time
}
});phasync::shielded#
phasync::shielded(function () use ($socket) {
fwrite($socket, $goodbye); // still sent during a shutdown
phasync::writable($socket, 1.0);
});CancelledException#
phasync::run(function () {
$worker = phasync::go(function () {
try {
phasync::sleep(10);
} catch (phasync\CancelledException $e) {
echo "cancelled: ", $e->getMessage(), "\n"; // shutting down
throw $e;
}
});
phasync::sleep(0.01);
phasync::cancel($worker, 'shutting down');
});