1
0
mirror of https://github.com/danog/amp.git synced 2024-12-02 17:37:50 +01:00
amp/docs/coroutines
2022-02-20 12:36:21 -06:00
..
README.md Update deprecated method name to new name 2022-02-20 12:36:21 -06:00

layout title permalink
docs Coroutines /coroutines/

Coroutines are interruptible functions. In PHP they can be implemented using Fibers.

{:.note}

Previous versions of Amp used Generators for a similar purpose, but fibers can be interrupted anywhere in the stack making previous helpers like Amp\call() unnecessary.

At any given time, only one fiber is running. When a coroutine suspends, execution of the coroutine is temporarily interrupted, allowing other tasks to be run. Execution is resumed once a timer expires, stream operations are possible, or any awaited Future completes.

<?php

require __DIR__ . '/vendor/autoload.php';

use Revolt\EventLoop;

$suspension = EventLoop::getSuspension();

EventLoop::delay(5, function () use ($suspension): void {
    print '++ Executing callback created by EventLoop::delay()' . PHP_EOL;

    $suspension->resume(null);
});

print '++ Suspending to event loop...' . PHP_EOL;

$suspension->suspend();

print '++ Script end' . PHP_EOL;

Suspending and resuming fibers is handled by the Suspension API of Revolt.

{:.note}

TODO: Note about futures on public APIs vs. awaiting them internally.