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.

PHP Coroutine is supported for Swoole version > 2.0 by default.

If you like to disable the coroutine feature, use --disable-coroutine when compiling the Swoole PHP extension.

Why Coroutine?

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

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 reqeust, 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:

Example code of Swoole Coroutine:

A simple HTTP server sending a TCP request to remote server then echo the result to http client.

$http = new swoole_http_server("", 9501);

$http->on("request", function ($request, $response) {
    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
    // swoole schedule trigger coroutine before connect
    $client->connect("", 8888, 0.5);
    $client->send("hello world from swoole");
   // swoole schedule trigger coroutine on recv
    $ret = $client->recv();
   $response->header("Content-Type", "text/plain");



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

Do not use Coroutine within these functions: