From d0ff66c9abe9d6abbca12fd811e0c3cb69c1033a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=80=E8=90=8C=E5=B0=8F=E6=B1=90?= Date: Fri, 22 Nov 2019 23:26:32 +0800 Subject: =?UTF-8?q?=E6=95=B4=E7=90=86=E4=B8=80=E4=B8=8B=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- script-beta/src/brave/brave.lua | 70 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 script-beta/src/brave/brave.lua (limited to 'script-beta/src/brave/brave.lua') diff --git a/script-beta/src/brave/brave.lua b/script-beta/src/brave/brave.lua new file mode 100644 index 00000000..08909074 --- /dev/null +++ b/script-beta/src/brave/brave.lua @@ -0,0 +1,70 @@ +local thread = require 'bee.thread' + +---@class pub_brave +local m = {} +m.type = 'brave' +m.ability = {} +m.queue = {} + +--- 注册成为勇者 +function m.register(id) + m.taskpad = thread.channel('taskpad' .. id) + m.waiter = thread.channel('waiter' .. id) + m.id = id + + if #m.queue > 0 then + for _, info in ipairs(m.queue) do + m.waiter:push(info.name, info.params) + end + end + m.queue = nil + + m.start() +end + +--- 注册能力 +function m.on(name, callback) + m.ability[name] = callback +end + +--- 报告 +function m.push(name, params) + if m.waiter then + m.waiter:push(name, params) + else + m.queue[#m.queue+1] = { + name = name, + params = params, + } + end +end + +--- 开始找工作 +function m.start() + m.push('mem', collectgarbage 'count') + while true do + local suc, name, id, params = m.taskpad:pop() + if not suc then + -- 找不到工作的勇者,只好睡觉 + thread.sleep(0.001) + goto CONTINUE + end + local ability = m.ability[name] + -- TODO + if not ability then + m.waiter:push(id) + log.error('Brave can not handle this work: ' .. name) + goto CONTINUE + end + local ok, res = xpcall(ability, log.error, params) + if ok then + m.waiter:push(id, res) + else + m.waiter:push(id) + end + m.push('mem', collectgarbage 'count') + ::CONTINUE:: + end +end + +return m -- cgit v1.2.3