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.
Use coroutine clients in the functions:
Use coroutine clients in
Some build-in methods.
Channels are used for communication between coroutines.
Run is the context to execute coroutines outside of server context.
Swoole Library is a group of Swoole Coroutine build-in functions implemented with PHP.
Swoole\Coroutine\Server is the coroutine version of
Swoole\Server. Multiple servers can be created within one Linux process.
Most popular clients are supported by Swoole Coroutine:
max_coro_num: The max number of coroutine created by the Swoole server. The default value is 3000.
Global variables: static global variables may change during coroutine switching.
Xdebug, xhprof, Blackfire can't be used for code profiling.
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