PHP code example of carno-php / coroutine

1. Go to this page and download the library: Download carno-php/coroutine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

carno-php / coroutine example snippets


function go(mixed $program, Context $ctx = null) : void

// use closure
go(function () {
    yield 'something';
    return 'done';
});

// with exceptions
try {
    go(function () {
        throw new Exception('test');
    });
} catch (Throwable $e) {
    echo 'got exception :: ', $e->getMessage(), PHP_EOL;
}

function co(mixed $program, Context $ctx = null) : Closure

$func = co(function (string $input) {
    yield 'something';
    echo $input;
});
$func('vars');

function async(mixed $program, Context $ctx = null, mixed ...$args) : Promised

async(function () {
    yield msleep(500);
})->then(function () {
    echo 'you will see me after 500ms', PHP_EOL;
});

function await(Closure $dial, Closure $awake,
    int $timeout = 60000, string $error = TimeoutException::class, string $message = '') : Promised

$async = function ($callback) {
    $callback(111, 222);
};
yield await(function (Closure $awake) use ($async) {
    $async($awake);
}, function (int $a, int $b) {
    echo 'a = ', $a, ' b = ', $b, PHP_EOL;
});

function timeout(int $ms, string $ec = TimeoutException::class, string $em = '') : Promised

yield race(timeout(rand(5, 10)), timeout(rand(5, 10), CustomException::class, 'custom message'));

function msleep(int $ms, Closure $do = null) : Promised

// make sleep
yield msleep(200);
// do something when wake
echo 'you will see hello -> ', yield msleep(300, function () {
    return 'hello';
}), PHP_EOL;

go(function () {
    echo 'hello ', (yield ctx())->get('hello'), PHP_EOL;
}, (new Context)->set('hello', 'world'));

yield (function () {
    yield defer(function ($stage) {
        // $stage is returned value or last yield value or throwable if exception
        echo 'in defer', PHP_EOL;
    });
    echo 'in end', PHP_EOL;
})();

yield race((function () {
    echo 'hello ', (yield ctx())->get('hello'), PHP_EOL;
})(), timeout(500), (new Context)->set('hello', 'world'));
bash
composer