Skip to content

Commit de6817d

Browse files
committed
修复TASK模块在遍历中途增删任务可能导致严重问题
1 parent 0dbd1be commit de6817d

1 file changed

Lines changed: 13 additions & 9 deletions

File tree

task.lua

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,15 @@ local tasks={}
7777
---Update all tasks (called by Zenitha)
7878
---@param dt number
7979
function TASK._update(dt)
80-
for i=#tasks,1,-1 do
80+
local i,n=1,#tasks
81+
while i<=n do
8182
local T=tasks[i]
82-
if status(T.thread)=='dead' then
83+
if not T or status(T.thread)=='dead' then
8384
rem(tasks,i)
85+
n=n-1
8486
else
8587
assert(resume(T.thread,dt))
88+
i=i+1
8689
end
8790
end
8891
end
@@ -104,7 +107,8 @@ function TASK.new(code,...)
104107
end
105108
end
106109

107-
---Get the number of tasks
110+
---Get the number of tasks
111+
---Warning: the result is not accurate during TASK._update, tasks removed during the update still count
108112
---@return number
109113
function TASK.getCount()
110114
return #tasks
@@ -113,9 +117,9 @@ end
113117
---Remove task(s) by specified code(the function which created the task)
114118
---@param code function
115119
function TASK.removeTask_code(code)
116-
for i=#tasks,1,-1 do
117-
if tasks[i].code==code then
118-
rem(tasks,i)
120+
for i=1,#tasks do
121+
if tasks[i] and tasks[i].code==code then
122+
tasks[i]=false
119123
end
120124
end
121125
end
@@ -124,9 +128,9 @@ end
124128
---@param func function
125129
---@param ... any Arguments passed to the given function
126130
function TASK.removeTask_iterate(func,...)
127-
for i=#tasks,1,-1 do
128-
if func(tasks[i],...) then
129-
rem(tasks,i)
131+
for i=1,#tasks do
132+
if tasks[i] and func(tasks[i],...) then
133+
tasks[i]=false
130134
end
131135
end
132136
end

0 commit comments

Comments
 (0)