美文网首页
OpenResty(一) 协程

OpenResty(一) 协程

作者: 印随2018 | 来源:发表于2019-07-31 15:33 被阅读0次

    在OpenResty项目中,一个请求对应一个Lua协程,各自互不干扰,又可以使用不同的方式来编写代码。

    其实上面的描述不太准确,实际上,只有在下面5个阶段才会创建新的协程

    • lua_access_by
    • lua_content_by
    • lua_rewrite_by

    这也是为什么,ngx_lua好几个指令只能运行在这三个阶段,比如


    下面看看lua_access_by是怎么启动协程的

    static ngx_int_t
    ngx_http_lua_access_by_chunk(lua_State *L, ngx_http_request_t *r)
    {
        ...
    
        /*  {{{ new coroutine to handle request */
        co = ngx_http_lua_new_thread(r, L, &co_ref);
    
        if (co == NULL) {
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "lua: failed to create new coroutine "
                          "to handle request");
    
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }
    
        /*  move code closure to new coroutine */
        lua_xmove(L, co, 1);
    
        /*  save nginx request in coroutine globals table */
        ngx_http_lua_set_req(co, r);
        
        ...
    }
    

    其他阶段注册的Lua代码都是在Lua虚拟机的主线程中完成的(不包括SSL部分,没仔细看)。

    相关文章

      网友评论

          本文标题:OpenResty(一) 协程

          本文链接:https://www.haomeiwen.com/subject/joxtdctx.html