swoole / library

📚 Swoole Library
https://wiki.swoole.com/#/library
Apache License 2.0
232 stars 59 forks source link

Introducing Futures #145

Open leocavalcante opened 2 years ago

leocavalcante commented 2 years ago

This PR introduces Futures as part of Swoole's standard library features.

Futures are abstractions on top of Coroutines providing alternative syntax for building concurrent programs with Swoole.

Main differences from Coroutines are:

Futures are lazy

They don't evaluate until you call await:

$future = Future\async(static function (): void {
    echo "are lazy\n";
});

Coroutine::create(static function (): void {
    echo 'Futures ';
});

echo $future->await();

Futures can return values

The Channel handling is done under the hood:

$future = Future\async(static function (): string {
    return Http\get('https://httpbin.org/get')->getBody();
});

echo $future->await();

Futures propagates exceptions

$future = Future\async(static function (): string {
    throw new RuntimeException('Futures propagates exceptions');
});

try {
    $future->await();
} catch (Throwable $e) {
    echo $e->getMessage();
}

Futures synchronization is similar

It uses Coroutine::join under the hood:

$future1 = \Swoole\Future::create(static function () {
    return \Swoole\Coroutine\Http\get('https://httpbin.org/delay/2')->getBody();
});

$future2 = \Swoole\Future::create(static function () {
    return \Swoole\Coroutine\Http\get('https://httpbin.org/delay/2')->getBody();
});

echo implode(PHP_EOL, \Swoole\Future::join([$future1, $future2]));
johanjanssens commented 2 years ago

@leocavalcante This is really nice work!