Swoole Coroutine

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 a 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 use sync programming style to archive the performance of async IO. Avoiding callback or multiple level callbacks in codes.

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

Coroutine execution context

Use coroutine clients in the functions: onRequest, onReceive, onConnect inside Swoole\Server or Swoole\HTTP\Server.

Use coroutine clients in Co\run context.

Swoole\Coroutine Modules

Swoole\Coroutine\Methods

Some build-in methods.

Swoole\Coroutine\Channel

Channels are used for communication between coroutines.

Swoole\Coroutine\Run

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

Swoole Coroutine Library

Swoole Library is a group of Swoole Coroutine build-in functions implemented with PHP.

Swoole Coroutine Server

Swoole\Coroutine\Server is the coroutine version of Swoole\Server. Multiple servers can be created within one Linux process.

Swoole Coroutine clients

Most popular clients are supported by Swoole Coroutine:

Configuration

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 the 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.