-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathasync.lua
More file actions
452 lines (399 loc) · 12.5 KB
/
async.lua
File metadata and controls
452 lines (399 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
-- _ _
-- | | __ _ _ _ / \ ___ _ _ _ __ ___
-- | | / _` | | | | / _ \ / __| | | | '_ \ / __|
-- | |__| (_| | |_| | / ___ \\__ \ |_| | | | | (__
-- |_____\__,_|\__,_| /_/ \_\___/\__, |_| |_|\___|
-- |___/
-- Author: rdququ
-- Github: https://github.com/dlqw/LuaAsync
-- Date: 2025-03-19
-- License: MIT
Async = {}
function Async.Init()
Async._taskQueue = {}
Async._pendingTaskQueue = {}
Async._currentTaskGroup = nil
-- Memory optimization consideration:
-- Task groups hold strong references to tasks until completion.
-- For long-running applications with many short-lived tasks, consider:
-- 1. Using weak references for completed tasks in task groups
-- 2. Implementing a task pool to reuse task objects
-- 3. Explicitly clearing task references after completion
-- Note: This requires careful design to avoid premature GC of active tasks
end
---@param deltaTime number
function Async.Update(deltaTime)
Async._taskQueue = {}
table.move(Async._pendingTaskQueue, 1, #Async._pendingTaskQueue, 1, Async._taskQueue)
Async._pendingTaskQueue = {}
for _, taskGroup in ipairs(Async._taskQueue) do
-- Create a new table each frame to collect continuing tasks
-- This ensures clean state and avoids modifying the original taskGroup
Async._currentTaskGroup = { _cancellationToken = taskGroup._cancellationToken }
local groupCancelled = taskGroup._cancellationToken and taskGroup._cancellationToken:IsCancellationRequested()
for i = 1, #taskGroup, 1 do
local value = taskGroup[i]
local isDead = coroutine.status(value._coroutine) == "dead"
if isDead then
-- Task already completed, just trigger completion
value:Complete()
elseif groupCancelled then
-- Task group is cancelled and task is not done - set cancelled status
value._result = nil
value._status = TaskStatus.Cancelled
value:Complete()
-- Don't re-insert cancelled tasks
else
local isDone, isSuspended = value:_moveNext(deltaTime)
if not isDone then
table.insert(Async._currentTaskGroup, value)
else
value:Complete()
end
end
end
if next(Async._currentTaskGroup) then
table.insert(Async._pendingTaskQueue, Async._currentTaskGroup)
end
end
end
---Waitable
local Waitable = {}
Waitable.__call = function(self)
if self._invoker == nil then
error("Waitable is already completed")
return self
end
for index, value in ipairs(self._invoker) do
value()
end
self._invoker = nil
return self
end
Waitable.__index = Waitable
-- Note: Don't set default _invoker and _callbacks on prototype to avoid inheritance issues
---Task Status Enum
TaskStatus = {
Created = "Created",
Running = "Running",
Completed = "Completed",
Cancelled = "Cancelled",
Faulted = "Faulted"
}
---Task
Task = {}
Task.__index = Task
---创建一个Task对象
---@param func function
---@param cancellationToken table
---@return table
function Task.new(func, cancellationToken)
-- Capture debug info for better error messages
local debugInfo = ""
if debug and debug.getinfo then
local info = debug.getinfo(2, "Sl")
if info then
debugInfo = string.format("created at %s:%d", info.short_src or "?", info.currentline or 0)
end
end
local task = setmetatable({
_coroutine = coroutine.create(func),
_cancellationToken = cancellationToken,
_waitable = setmetatable({ _invoker = { Task._coroutine }, _callbacks = {}, _result = nil }, Waitable),
_result = nil,
_hasUsed = false,
_status = TaskStatus.Created,
_debugInfo = debugInfo
}, Task);
task._result = task._waitable._result -- 成员而非继承
return task
end
function Task:GetStatus()
return self._status
end
---@return boolean isDone
---@return boolean isSuspended
function Task:_moveNext(deltaTime)
if self._cancellationToken ~= nil then
if self._cancellationToken:IsCancellationRequested() then
self._result = nil
self._status = TaskStatus.Cancelled
return true, false
end
end
self._status = TaskStatus.Running
local success, result = coroutine.resume(self._coroutine, deltaTime)
self._result = result
if not success then
self._status = TaskStatus.Faulted
error(result)
return true, false
end
local isDead = coroutine.status(self._coroutine) == "dead"
if isDead then
self._status = TaskStatus.Completed
end
return isDead, coroutine.status(self._coroutine) == "suspended"
end
function Task:setWaitable(waitable)
self._waitable = waitable
end
function Task:OnCompleted(callback)
self._waitable:OnCompleted(callback)
return self
end
Task.__call = function(self)
return self:Start()
end
function Waitable:OnCompleted(callback)
if not self._callbacks then
self._callbacks = {}
end
table.insert(self._callbacks, callback)
return self
end
function Waitable:Complete()
if self._callbacks then
for index, value in ipairs(self._callbacks) do
value()
end
self._callbacks = nil -- Consistent with _invoker = nil in __call
end
return self
end
function Task:Complete()
self._waitable:Complete()
return self
end
function Waitable:ToTask(cancellationToken)
return Task.new(function()
Await(self)
end, cancellationToken or self._cancellationToken)
end
---Core
---创建一个已经完成的Task对象
---@param result any
---@return table task
function Task.FromResult(result)
local task = setmetatable({
_coroutine = nil,
_cancellationToken = nil,
_waitable = setmetatable({ _invoker = nil, _callbacks = nil, _result = result }, Waitable),
_result = result,
_hasUsed = true,
_status = TaskStatus.Completed
}, Task)
return task
end
---将传入工作加入队列, 并返回一个Task对象
---@param func function
---@param cancellationToken table
---@return table task
function Task.Run(func, cancellationToken)
local task = Task.new(func, cancellationToken)
local newTaskGroup = { task }
newTaskGroup._cancellationToken = cancellationToken
table.insert(Async._pendingTaskQueue, newTaskGroup)
return task
end
---@return table task
function Task:Start()
if self._hasUsed then
local msg = "Task is already started or completed"
if self._debugInfo and self._debugInfo ~= "" then
msg = msg .. " (" .. self._debugInfo .. ")"
end
error(msg)
return self
end
self._hasUsed = true
local newTaskGroup = { self }
newTaskGroup._cancellationToken = self._cancellationToken
table.insert(Async._pendingTaskQueue, newTaskGroup)
return self
end
---@return table task
function Task.RunAsSub(func, cancellationToken)
local task = Task.new(func, cancellationToken)
local targetTaskGroup = Async._currentTaskGroup
if (targetTaskGroup == nil) then
targetTaskGroup = Async._pendingTaskQueue[#Async._pendingTaskQueue]
if (targetTaskGroup == nil) then
error("RunAsSub must be called in a Task")
return task
end
end
table.insert(targetTaskGroup, task)
return task
end
---@return table task
function Task:StartAsSub()
if self._hasUsed then
local msg = "Task is already started or completed"
if self._debugInfo and self._debugInfo ~= "" then
msg = msg .. " (" .. self._debugInfo .. ")"
end
error(msg)
return self
end
self._hasUsed = true
local targetTaskGroup = Async._currentTaskGroup
if (targetTaskGroup == nil) then
targetTaskGroup = Async._pendingTaskQueue[#Async._pendingTaskQueue]
if (targetTaskGroup == nil) then
error("StartAsSub must be called in a Task")
return self
end
end
table.insert(targetTaskGroup, self)
return self
end
---@return any result
function Await(waitable)
waitable()
coroutine.yield()
return waitable._result
end
function Waitable:Forget()
self()
end
function Task:Forget()
self()
end
---@return table waitable
function Task.NextFrame(cancellationToken)
local waitable = setmetatable({
_callbacks = {},
_result = nil
}, Waitable)
waitable._invoker = { function()
Task.RunAsSub(function()
coroutine.yield()
end, cancellationToken):setWaitable(waitable)
end }
return waitable
end
---@return table waitable
function Task.Delay(milliseconds, cancellationToken)
local waitable = setmetatable({
_timer = 0,
_duration = milliseconds / 1000,
_callbacks = {},
_result = nil
}, Waitable)
waitable._invoker = { function()
Task.RunAsSub(function()
while waitable._timer < waitable._duration do
waitable._timer = waitable._timer + coroutine.yield()
end
end, cancellationToken):setWaitable(waitable)
end }
return waitable
end
---@param condition function
---@return table waitable
function Task.Until(condition, cancellationToken)
local waitable = setmetatable({
_callbacks = {},
_result = nil
}, Waitable)
waitable._invoker = { function()
Task.RunAsSub(function()
while not condition() do
coroutine.yield()
end
end, cancellationToken):setWaitable(waitable)
end }
return waitable
end
---waitable返回的结果为存储所有任务结果的表, 可以使用 table.unpack 解包
---@param ... table @Task
---@return table waitable
function Task.WhenAll(cancellationToken, ...)
local tasks = { ... }
local waitable = setmetatable({
_completedCount = #tasks,
_callbacks = {},
_invoker = {},
_result = {}
}, Waitable)
waitable._invoker = { function()
for index, task in ipairs(tasks) do
task._waitable:OnCompleted(function()
waitable._completedCount = waitable._completedCount - 1
waitable._result[index] = task._result
end)
-- Only start task if not already started
if not task._hasUsed then
task:Start()
end
end
Task.RunAsSub(function()
while waitable._completedCount > 0 do
coroutine.yield()
end
return waitable._result
end, cancellationToken):setWaitable(waitable)
end }
return waitable
end
---waitable返回的结果为第一个完成的任务的索引
---@param ... table @Task
---@return table waitable
function Task.WhenAny(cancellationToken, ...)
local tasks = { ... }
local waitable = setmetatable({
_first = nil,
_callbacks = {},
_invoker = {},
_result = nil
}, Waitable)
waitable._invoker = { function()
for index, task in ipairs(tasks) do
task._waitable:OnCompleted(function()
if waitable._first == nil then
waitable._first = index
end
end)
-- Only start task if not already started
if not task._hasUsed then
task:Start()
end
end
Task.RunAsSub(function()
while not waitable._first do
coroutine.yield()
end
waitable._result = waitable._first
end, cancellationToken):setWaitable(waitable)
end }
return waitable
end
---CancellationToken
local CancellationToken = {}
CancellationToken.__index = CancellationToken
function CancellationToken.new()
return setmetatable({
_isCancellationRequested = false
}, CancellationToken)
end
function CancellationToken:Cancel()
self._isCancellationRequested = true
end
function CancellationToken:IsCancellationRequested()
return self._isCancellationRequested
end
---CancellationTokenSource
CancellationTokenSource = {}
CancellationTokenSource.__index = CancellationTokenSource
function CancellationTokenSource.new()
return setmetatable({
_token = CancellationToken.new()
}, CancellationTokenSource)
end
function CancellationTokenSource:Cancel()
self._token:Cancel()
end
function CancellationTokenSource:GetToken()
return self._token
end