Open leocavalcante opened 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:
They don't evaluate until you call await:
await
$future = Future\async(static function (): void { echo "are lazy\n"; }); Coroutine::create(static function (): void { echo 'Futures '; }); echo $future->await();
The Channel handling is done under the hood:
Channel
$future = Future\async(static function (): string { return Http\get('https://httpbin.org/get')->getBody(); }); echo $future->await();
$future = Future\async(static function (): string { throw new RuntimeException('Futures propagates exceptions'); }); try { $future->await(); } catch (Throwable $e) { echo $e->getMessage(); }
It uses Coroutine::join under the hood:
Coroutine::join
$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]));
@leocavalcante This is really nice work!
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
:Futures can return values
The
Channel
handling is done under the hood:Futures propagates exceptions
Futures synchronization is similar
It uses
Coroutine::join
under the hood: