【问题标题】:How to make Nginx wait for a thread pool task如何让 Nginx 等待线程池任务
【发布时间】:2019-09-18 09:11:51
【问题描述】:

我正在编写一个模块来处理我的 http 请求。为此,我在我的模块中添加了位置内容处理程序(或位置指令处理程序)。我的内容处理程序与一个非异步的库接口。所以在处理程序中,我将一个任务排队到 nginx 线程池。我还添加了一个线程完成处理程序。

我遇到的问题是 Nginx 没有等待我的线程完成。在我的位置内容处理程序中,我将任务排队并返回 NGX_DONE,Nginx 在线程运行时完成我的请求。我还尝试在 HTTP_CONTENT_PHASE 处理程序而不是位置内容处理程序中连接这个处理程序代码,但到目前为止还没有运气。

如何让 Nginx 在完成 HTTP_CONTENT_PHASE 中的请求之前等待我的线程完成?

【问题讨论】:

  • 伙计们,有人可以帮忙吗?即使是关于在哪里挖掘此信息的指针也会有所帮助和赞赏。

标签: nginx threadpool


【解决方案1】:

我终于找到了解决办法。这是一些相关的sn-p代码。

从 http 请求处理程序(或位置指令处理程序)排队任务到线程

typedef struct {

    ngx_http_request_t  *pHttpRequest;

} ngx_thread_ctx;


    static ngx_int_t ngx_http_rdm_agent_handler(ngx_http_request_t *r)
    {
        ngx_thread_task_t    *task;
        ngx_thread_ctx *thread_ctx; // Thread context is my struct                                         
                                   // that has pointer to nginx_request_t struct
        ..........
        ..........  
        thread_ctx = (ngx_thread_ctx*)(task->ctx);
        thread_ctx->pHttpRequest = r;

        task->handler = my_thread_callback;
        task->event.handler = my_thread_completion;
        task->event.data = thread_ctx;

        //*** This is the key part. Increment this so nginx
        //*** won't finalize request (r)
        r->main->blocked++;

        // loc_cf -> location config struct where I added thread pool during 
        // configuration phase
        if (ngx_thread_task_post(loc_cf->pThreadPool, task) != NGX_OK) {
            r->main->blocked--;
            return NGX_ERROR;
        }

        return NGX_DONE;
    }

线程的完成处理程序

static void my_thread_completion(ngx_event_t *ev) 
{

    ngx_thread_ctx *ctx = (ngx_thread_ctx*)ev->data;    

    ctx->pHttpRequest->main->blocked--;

    ngx_http_finalize_request(ctx->pHttpRequest, NGX_DONE);
}

【讨论】:

    猜你喜欢
    • 2015-07-13
    • 2011-06-02
    • 2016-05-01
    • 1970-01-01
    • 2020-03-27
    • 2019-10-08
    • 2021-01-06
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多