Swoole PHP Coroutine

Swoole Coroutine is similar to Coroutine in the other lanaguge or frameworks. Swoole creates one coroutine for each reqeust and schedule mainly based on IO status of each request.

Why Coroutine?

Please compare the difference between callback version and coroutine version in the example bellow.

Channel

Channel can be used to sync multiple coroutines:

<?php
$c = new chan(1);
$c->push($data);
$c->pop();

Coroutine API

PHP build-in functions like sleep using syscall are not blocking and should not be used in Swoole Coroutine context. You have use the coroutine version API:

<?php
Co::sleep(1);
Co::fread($fp);
Co::gethostbyname('www.google.com');

How to use coroutine in Swoole

The following client are supported with Coroutine:

You can also write your own client with Swoole TCP or UDP coroutine client.

Swoole\Server and Swoole\HTTP\Server createS one coroutine for each request / connection, then maintain and schedule the request based on client side IO status within Swoole\Server or Swoole\HTTP\Server.

You can use coroutine client within the following callback functions:

  • onRequet
  • onReceive
  • onConnect

Example code of Swoole Coroutine:

<?php
<?php
$server = new Swoole\Http\Server("127.0.0.1", 9502, SWOOLE_BASE);

$server->set([
    'worker_num' => 1,
]);

$server->on('Request', function ($request, $response) {

    $tcpclient = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
    $tcpclient->connect('127.0.0.1', 95010.5)
    $tcpclient->send("hello world\n");

    $redis = new Swoole\Coroutine\Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->setDefer();
    $redis->get('key');

    $mysql = new Swoole\Coroutine\MySQL();
    $mysql->connect([
        'host' => '127.0.0.1',
        'user' => 'user',
        'password' => 'pass',
        'database' => 'test',
    ]);
    $mysql->setDefer();
    $mysql->query('select sleep(1)');

    $httpclient = new Swoole\Coroutine\Http\Client('0.0.0.0', 9599);
    $httpclient->setHeaders(['Host' => "www.swoole.co.uk"]);
    $httpclient->set([ 'timeout' => 1]);
    $httpclient->setDefer();
    $httpclient->get('/');

    $tcp_res  = $tcpclient->recv();
    $redis_res = $redis->recv();
    $mysql_res = $mysql->recv();
    $http_res  = $httpclient->recv();

    $response->end('End');
});
$server->start();

Note

The following extensions have to be disabled to use Swoole Coroutine:

  • xdebug
  • phptrace
  • aop
  • molten
  • xhprof

Swoole Coroutine documents: https://www.swoole.co.uk/docs/modules/swoole-coroutine