本文簡單介紹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);
}