Skip to content

Commit 51ddc32

Browse files
committed
feature: supported wait any uthreads for ngx.thread.wait
1 parent 9bee7e7 commit 51ddc32

File tree

2 files changed

+58
-5
lines changed

2 files changed

+58
-5
lines changed

src/ngx_http_lua_uthread.c

+7-5
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ ngx_http_lua_uthread_spawn(lua_State *L)
104104
static int
105105
ngx_http_lua_uthread_wait(lua_State *L)
106106
{
107-
int i, nargs, nrets;
107+
int i, nargs, nrets, dead_count;
108108
lua_State *sub_co;
109109
ngx_http_request_t *r;
110110
ngx_http_lua_ctx_t *ctx;
@@ -129,6 +129,8 @@ ngx_http_lua_uthread_wait(lua_State *L)
129129
return luaL_error(L, "at least one coroutine should be specified");
130130
}
131131

132+
dead_count = 0;
133+
132134
for (i = 1; i <= nargs; i++) {
133135
sub_co = lua_tothread(L, i);
134136

@@ -172,11 +174,11 @@ ngx_http_lua_uthread_wait(lua_State *L)
172174
return nrets;
173175

174176
case NGX_HTTP_LUA_CO_DEAD:
175-
dd("uthread already waited: %p (parent %p)", sub_coctx,
176-
coctx);
177+
dd("uthread already waited: %p (parent %p), dead/total: %d/%d",
178+
sub_coctx, coctx, dead_count + 1, nargs);
177179

178-
if (i < nargs) {
179-
/* just ignore it if it is not the last one */
180+
if (++dead_count < nargs) {
181+
/* just ignore it if not all threads are dead */
180182
continue;
181183
}
182184

t/098-uthread-wait.t

+51
Original file line numberDiff line numberDiff line change
@@ -1340,3 +1340,54 @@ GET /lua
13401340
at least one coroutine should be specified
13411341
--- no_error_log
13421342
[crit]
1343+
1344+
1345+
1346+
=== TEST 24: wait any uthreads
1347+
--- config
1348+
location /lua {
1349+
content_by_lua '
1350+
local function f(seconds, tag)
1351+
-- ngx.say("hello in thread")
1352+
ngx.sleep(seconds)
1353+
return tag, seconds
1354+
end
1355+
local threads_args = {
1356+
{ 1, 't1 wait 1 seconds'},
1357+
{ 0.2, 't2 wait 0.2 seconds'},
1358+
{ 3, 't3 wait 3 seconds'},
1359+
{ 2, 't4 wait 2 seconds'},
1360+
{ 0.5, 't5 wait 0.5 seconds'},
1361+
}
1362+
local threads = {}
1363+
for i, args in ipairs(threads_args) do
1364+
local t, err = ngx.thread.spawn(f, args[1], args[2])
1365+
if not t then
1366+
ngx.say("failed to spawn thread: ", err)
1367+
break
1368+
end
1369+
threads[i] = t
1370+
end
1371+
1372+
for i = 1, #threads + 1 do
1373+
local ok, res = ngx.thread.wait(unpack(threads))
1374+
if not ok then
1375+
ngx.say("failed to run thread: ", res)
1376+
break
1377+
end
1378+
1379+
ngx.say(i, ": ", res)
1380+
end
1381+
';
1382+
}
1383+
--- request
1384+
GET /lua
1385+
--- response_body
1386+
1: t2 wait 0.2 seconds
1387+
2: t5 wait 0.5 seconds
1388+
3: t1 wait 1 seconds
1389+
4: t4 wait 2 seconds
1390+
5: t3 wait 3 seconds
1391+
failed to run thread: already waited or killed
1392+
--- no_error_log
1393+
[error]

0 commit comments

Comments
 (0)