Swoole PHP Coroutine

Swoole Coroutine is similar to Coroutine in the other lanaguge or frameworks. Swoole create one coroutine for each reqeust and schedule based on IO status. It is not necessary to use callback in the server side logic.

Why Coroutine?

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


Channel can be used to sync multiple coroutines:

$c = new chan(1);

Coroutine API

PHP build-in functions like sleep are not supported by Swoole, please use the coroutine version API:


How to use coroutine in Swoole

The following client are supported in Swoole Coroutine:

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

swoole_server and swoole_http_server create one coroutine for each request, then maintain and schedule the request based on client side IO status within swoole_server and swoole_http_server.

You can use coroutine client within the following callback functions:

  • onRequet
  • onReceive
  • onConnect

Example code of Swoole Coroutine:

$server = new Swoole\Http\Server("", 9502, SWOOLE_BASE);

    'worker_num' => 1,

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

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

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

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

    $httpclient = new Swoole\Coroutine\Http\Client('', 9599);
    $httpclient->setHeaders(['Host' => "api.mp.qq.com"]);
    $httpclient->set([ 'timeout' => 1]);

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

    $response->end('Test End');


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

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