Co\run and Coroutine Context

Coroutines should only be executed within a Coroutine Context.

Co\run create the context to execute coroutines. Coroutine context can also be created at the Server callback function.

Co\run is designed to replace the patten go() + Swoole\Event::wait() as a context for executing coroutines.

Example

<?php
Co\run(function() {
    go(function() {
        Co::sleep(1);
        echo "Done 1\n";
    });
    go(function() {
        Co::sleep(1);
        echo "Done 2\n";
    });
});

Swoole\Coroutine\Scheduler

Coroutine Scheduler creates multiple coroutine context.

Co\run is a simple way to create only one coroutine context.

Example

<?php

# multiple context

$run = new Swoole\Coroutine\Scheduler;

$run->add(function () {
    Co::sleep(1);
    echo "Done 1.\n";
});
$run->add(function () {
    Co::sleep(1);
    echo "Done 2.\n";
});
$run->start();

# or

Co\run(function() {
    Co::sleep(1);
    echo "Done.\n";
});