本文简单介绍cosocket在的实现原理。
一、Resume
nginx的C运行时
切换到Lua运行时
的核心代码
ngx_http_lua_socket_tcp.c
/* Read Event */
static ngx_int_t
ngx_http_lua_socket_tcp_read_resume(ngx_http_request_t *r)
{
return ngx_http_lua_socket_tcp_resume_helper(r, SOCKET_OP_READ);
}
/* Write Event */
static ngx_int_t
ngx_http_lua_socket_tcp_write_resume(ngx_http_request_t *r)
{
return ngx_http_lua_socket_tcp_resume_helper(r, SOCKET_OP_WRITE);
}
static ngx_int_t
ngx_http_lua_socket_tcp_resume_helper(ngx_http_request_t *r, int socket_op)
{
lua_State *vm;
ngx_http_lua_ctx_t *ctx;
...
ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
vm = ngx_http_lua_get_lua_vm(r, ctx);
rc = ngx_http_lua_run_thread(vm, r, ctx, nret);
...
}
二、Yield
nginx的Lua运行时
切换到C运行时
的核心代码。
注意: lua语言中无法直接把执行权限让出给C运行时,只能借助注入到Lua环境的C代码来实现。
ngx_http_lua_socket_tcp.c
lua_pushcfunction(L, ngx_http_lua_socket_tcp_receive);
static int
ngx_http_lua_socket_tcp_receive(lua_State *L)
{
....
return ngx_http_lua_socket_tcp_receive_helper(r, u, L);
}
static int
ngx_http_lua_socket_tcp_receive_helper(ngx_http_request_t *r,
ngx_http_lua_socket_tcp_upstream_t *u, lua_State *L)
{
......
return lua_yield(L, 0);
}