phasync
Cancellation and cleanup / Examples

Cancellation and cleanup

Examples

Every example of this topic, with its output.

phasync::finally#

Example 1
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#

Example 1
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#

Example 1
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#

Example 1
phasync::go(function () use ($server) {
    phasync::signal([SIGTERM, SIGINT]);
    $server->close();   // stop accepting, let the requests in flight finish
});

phasync::onSignal#

Example 1
phasync::onSignal(SIGQUIT, function () {
    error_log('stuck at ' . (new Exception())->getTraceAsString());
});

phasync::shutdown#

Example 1
phasync::go(function () {
    phasync::signal(SIGTERM);
    if (phasync::shutdown(2.0) > 0) {
        exit(1);   // some coroutines didn't stop in time
    }
});

phasync::shielded#

Example 1
phasync::shielded(function () use ($socket) {
    fwrite($socket, $goodbye);   // still sent during a shutdown
    phasync::writable($socket, 1.0);
});

CancelledException#

Example 1
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');
});