summaryrefslogtreecommitdiff
path: root/server-beta/src/task.lua
blob: c7950e44a78cce5ad9bbe3ba5a7f84925a597013 (plain)
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
local timer  = require 'timer'

---@class task
local m = {}
m.type = 'task'

m.coTracker = setmetatable({}, { __mode = 'k' })

--- 设置错误处理器
---@param errHandle function {comment = '当有错误发生时,会以错误堆栈为参数调用该函数'}
function m.setErrorHandle(errHandle)
    m.errorHandle = errHandle
end

--- 创建一个任务
function m.create(callback)
    local co = coroutine.create(callback)
    m.coTracker[co] = true
    local suc, err = coroutine.resume(co)
    if not suc and m.errorHandle then
        m.errorHandle(debug.traceback(co, err))
    end
end

--- 休眠一段时间
---@param time number
function m.sleep(time)
    local co, main = coroutine.running()
    if main then
        if m.errorHandle then
            m.errorHandle(debug.traceback('Cant sleep in main thread'))
        end
        return
    end
    timer.wait(time, function ()
        local suc, err = coroutine.resume(co)
        if not suc and m.errorHandle then
            m.errorHandle(debug.traceback(co, err))
        end
    end)
    return coroutine.yield()
end

--- 等待直到唤醒
---@param waker function
function m.wait(waker)
    local co, main = coroutine.running()
    if main then
        if m.errorHandle then
            m.errorHandle(debug.traceback('Cant wait in main thread'))
        end
        return
    end
    waker(function (...)
        local suc, err = coroutine.resume(co, ...)
        if not suc and m.errorHandle then
            m.errorHandle(debug.traceback(co, err))
        end
    end)
    return coroutine.yield()
end

return m