Openresty利用ngx.thread判断超时

如果有需求在lua运行期间设置i/o的超时,可以利用go语言goroutine的思路,做一个超时判断,代码如下:

function timeout()
ngx.sleep(1)
ngx.say(“timeout”)
return “timeout”
end

function doSomeIo()
ngx.sleep(2)
ngx.say(“doSomeIo”)
return “doSomeIo”
end

local t, err = ngx.thread.spawn(timeout)
local d, err = ngx.thread.spawn(doSomeIo)

ok, res = ngx.thread.wait(d,t) – 这行代码表示优先接受返回的 coroutine
ngx.thread.kill(t)
ngx.thread.kill(d)

ngx.say(res) //这个例子应该是 timeout

上面这些简单的代码,就可以很容易的做到判断超时了
另外需要注意:
ngx.thread.wait 这个等待只能在调用 ngx.thread.spawn 的父coroutine里等待