OpenResty cosocket

本文簡單介紹cosocket在的實現(xiàn)原理。


一、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語言中無法直接把執(zhí)行權(quán)限讓出給C運行時,只能借助注入到Lua環(huán)境的C代碼來實現(xiàn)。

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);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容