Swoole-2.0
基于setjmp
、longjmp
实现,在进行协程切换时会自动保存Zend VM
的内存状态(主要是EG
全局内存和vm stack
)。
setjmp
和longjmp
主要是用于从ZendVM
的C
堆栈跳回Swoole
的C
回调函数Swoole-4.0
重构了协程内核,实现了C
栈和PHP
栈同时保存和切换,支持所有PHP
语法。
$server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);
#1
$server->on('Request', function($request, $response) {
$mysql = new Swoole\Coroutine\MySQL();
#2
$res = $mysql->connect([
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'database' => 'test',
]);
#3
if ($res == false) {
$response->end("MySQL connect fail!");
return;
}
$ret = $mysql->query('show tables', 2);
$response->end("swoole response is ok, result=".var_export($ret, true));
});
$server->start();
onRequest
事件回调函数时,底层会调用C函数coro_create
创建一个协程(#1位置),同时保存这个时间点的CPU寄存器状态和ZendVM stack信息。mysql->connect
时发生IO操作,底层会调用C函数coro_save
保存当前协程的状态,包括Zend VM上下文以及协程描述信息,并调用coro_yield
让出程序控制权,当前的请求会挂起(#2位置)coro_resume
恢复对应的协程,恢复ZendVM上下文,继续向下执行PHP代码(#3位置)mysql->query
的执行过程与mysql->connect
一致,也会进行一次协程切换调度end
方法返回结果,并销毁此协程相比普通的异步回调程序,协程多增加额外的内存占用。
Ubuntu16.04 + Core I5 4核 + 8G内存 PHP7.0.10
ab -c 100 -n 10000 http://127.0.0.1:9501/
测试结果:
Server Software: swoole-http-server
Server Hostname: 127.0.0.1
Server Port: 9501
Document Path: /
Document Length: 348 bytes
Concurrency Level: 100
Time taken for tests: 0.883 seconds
Complete requests: 10000
Failed requests: 168
(Connect: 0, Receive: 0, Length: 168, Exceptions: 0)
Total transferred: 4914560 bytes
HTML transferred: 3424728 bytes
Requests per second: 11323.69 [#/sec] (mean)
Time per request: 8.831 [ms] (mean)
Time per request: 0.088 [ms] (mean, across all concurrent requests)
Transfer rate: 5434.67 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.2 0 2
Processing: 0 9 9.6 6 96
Waiting: 0 9 9.6 6 96
Total: 0 9 9.6 6 96
Percentage of the requests served within a certain time (ms)
50% 6
66% 9
75% 11
80% 12
90% 19
95% 27
98% 43
99% 51
100% 96 (longest request)