|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local copas = require("copas")
|
|
|
local pack = table.pack or function(...) return {n=select('#',...),...} end
|
|
|
local unpack = function(t) return (table.unpack or unpack)(t, 1, t.n or #t) end
|
|
|
|
|
|
local pcall = pcall
|
|
|
if _VERSION=="Lua 5.1" and not jit then
|
|
|
pcall = require("coxpcall").pcall
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local function add(self, task, ...)
|
|
|
local carg = pack(...)
|
|
|
local coro = copas.addthread(function()
|
|
|
copas.sleep(-1)
|
|
|
local suc, err = pcall(task, unpack(carg))
|
|
|
self:removethread(coroutine.running())
|
|
|
if not suc then error(err) end
|
|
|
end)
|
|
|
table.insert(self.queue, coro)
|
|
|
self:next()
|
|
|
return coro
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local function remove(self, coro)
|
|
|
self.queue[coro] = nil
|
|
|
if self.running[coro] then
|
|
|
|
|
|
self.running[coro] = nil
|
|
|
self.count = self.count - 1
|
|
|
else
|
|
|
|
|
|
for i, item in ipairs(self.queue) do
|
|
|
if coro == item then
|
|
|
table.remove(self.queue, i)
|
|
|
break
|
|
|
end
|
|
|
end
|
|
|
end
|
|
|
self:next()
|
|
|
end
|
|
|
|
|
|
|
|
|
local function nxt(self)
|
|
|
while self.count < self.maxt do
|
|
|
local coro = self.queue[1]
|
|
|
if not coro then break end
|
|
|
|
|
|
table.remove(self.queue, 1)
|
|
|
self.running[coro] = coro
|
|
|
self.count = self.count + 1
|
|
|
copas.wakeup(coro)
|
|
|
end
|
|
|
if self.count == 0 and next(self.waiting) then
|
|
|
|
|
|
for coro in pairs(self.waiting) do
|
|
|
copas.wakeup(coro)
|
|
|
end
|
|
|
end
|
|
|
end
|
|
|
|
|
|
|
|
|
local function wait(self)
|
|
|
if self.count == 0 then return end
|
|
|
local coro = coroutine.running()
|
|
|
|
|
|
self.waiting[coro] = true
|
|
|
copas.sleep(-1)
|
|
|
self.waiting[coro] = nil
|
|
|
end
|
|
|
|
|
|
|
|
|
local function new(maxt)
|
|
|
return {
|
|
|
maxt = maxt or 99999,
|
|
|
count = 0,
|
|
|
queue = {},
|
|
|
running = {},
|
|
|
waiting = {},
|
|
|
addthread = add,
|
|
|
removethread = remove,
|
|
|
next = nxt,
|
|
|
wait = wait,
|
|
|
}
|
|
|
end
|
|
|
|
|
|
return { new = new }
|
|
|
|
|
|
|