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.
Some build-in methods.
Channels are used for communcation between coroutines.
Run is the context to execute coroutines outside of server context.
Swoole Library is a group of Swoole Coroutine build-in functions implmeneted with PHP.
Most popular clients are supported by Swoole Coroutine:
PHP version: PHP 7.0+
Use coroutine clients in the functions:
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 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