如何让 Nginx 等待线程池任务 [英] How to make Nginx wait for a thread pool task

查看:55
本文介绍了如何让 Nginx 等待线程池任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a module that will handle the my http request. For this, I added a location content handler (or location directive handler) in my module. My content handler interfaces with a library which is not asynchronous. So within handler, I queue up a task to nginx thread pool. I also added a thread completion handler.

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

The problem I am running into is that Nginx doesn't wait for my thread to finish. With in my location content handler, I queue up task and return NGX_DONE and Nginx finalizes my request while thread is running. I also tried hooking up this handler code in HTTP_CONTENT_PHASE handler instead of location content handler, but no luck so far yet.

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

How can I make Nginx wait for my thread to finish before finalizing the request in HTTP_CONTENT_PHASE?

推荐答案

我终于找到了解决方案.这是一些相关的代码片段.

I have finally found the solution. Here is some relevant snippet of code.

从 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);
}

这篇关于如何让 Nginx 等待线程池任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆