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);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容