Swoole Coroutine

Suggested version: PHP: 7.1+ and Swoole: 4.4.0+

Coroutines are computer-program components that generalize subroutines for non-preemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations.

It is purely user mode thread. Compare with thread or process, all the operations in coroutines are happening in user mode, so the cost to create or switch coroutines are cheaper.

Swoole creates one coroutine for each request to the server, switches coroutines based on IO status.

The advantages of Swoole coroutines are:

  • Developers can user sync programming style to archive the performance of async IO. Avoiding callback or multiple level callback in codes.

  • Compare with coroutines in PHP lanaguge, yield is not necessary in the codes for IO switching. It is more convenient.

Swoole\Coroutine Modules

Swoole\Coroutine\Methods

Some build-in methods.

Swoole\Coroutine\Channel

Channels are used for communcation between coroutines.

Swoole\Coroutine\Run

Run is the context to execute coroutines outside of server context.

Swoole Coroutine clients

Most popular clients are supported by Swoole Coroutine:

How to enable Coroutine

PHP version: PHP 7.0+

Use coroutine clients in the functions: onRequest, onReceive, onConnect inside swoole_server or swoole_http_server.

Configurations

max_coro_num: The max number of coroutine created by the Swoole server. The default value is 3000.

Notices

  • Global variables: static global variables may change during coroutine switching.

  • Xdebug, xhprof, blackfire can't be used for code profiling.

Create new coroutine with go method

Why coroutine is important

Concurrency

Think about the situation when you want to get some data from both Redis server, and MySQL server.

The normal process is: redis send data->redis receive data->mysql send data->mysql receive data.

The time cost of the above process is the IO time of Redis + IO time of MySQL.

With coroutine clients, we can reduce the latency: redis send data/mysql send data->redis receive data/mysql receive data.

The time cost of the process is the max IO time of Redis and MySQL.

setDefer can be used to delay the receive operation.