OpenResty cosocket

本文簡單介紹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);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。