openresty / lua-nginx-module

Embed the Power of Lua into NGINX HTTP servers
https://openresty.org/
11.32k stars 2.04k forks source link

stop child thread when main request teminated #1196

Open aholic opened 6 years ago

aholic commented 6 years ago

hello, i am meeting this problem:

  1. start thread A to pull data from ip1 (eg. use http.lua)
  2. start thread B to pull data from ip2
  3. wait on A and B
  4. main request terminate
  5. the A and B will not stop

how can i stop A and B when main request ternimated ?

aholic commented 6 years ago

if there is a method for a coroutine to get his parent, that's ok....

is there any way to work around?

agentzh commented 6 years ago

@aholic Maybe you need to use ngx.on_abort and ngx.thread.kill?

aholic commented 6 years ago

do you mean code like this ?

    ngx.on_abort(function()
        ngx.log(ngx.ERR, 'on_abort')
        ngx.log(ngx.ERR, 'kill: ', ngx.thread.kill(th))
    end)

it will get a killer not parent error...

agentzh commented 6 years ago

@aholic Apparently you need to notify the parent thread from within your on_abort() thread to kill its own children or notify the children to stop processing when they are convenient.

Another brutal way is just to call ngx.exit(444) in side your on_abort() handler.

Making ngx.thread.kill() to work on any light threads is still a TODO and there is a pending PR for it: #476

aholic commented 6 years ago

@agentzh but if the client has gone, there's no chance for the parent thread to run because the parent thread is blocked on ngx.thread.wait() .... how to notify the parent thread from within on_abort() ?

agentzh commented 6 years ago

See my previous comment for alternatives.