Coroutine in PHP

Open Swoole Coroutine is similar to Coroutine in the other lanaguge or frameworks. OpenSwoole 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 OpenSwoole 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 OpenSwoole

The following client are supported with Coroutine:

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

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

You can use coroutine client within the following callback functions:

  • onRequet
  • onReceive
  • onConnect

Example code of OpenSwoole Coroutine:

Note

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

  • xdebug
  • phptrace
  • aop
  • molten
  • xhprof

Swoole Coroutine documents: https://openswoole.com/docs/modules/swoole-coroutine