Lua 协程池的简易实现。通过复用已完成的协程对象来避免频繁创建和销毁协程带来的开销。核心思路是让协程在执行完用户函数后不退出,而是通过 coroutine.yield 挂起等待下一次分配,从而实现协程的池化复用。
-- coroutine_pool.lua
local CoroutinePool = {}
-- 私有变量
local coroutinePool = {}
-- 私有函数
local function createCoroutine()
return coroutine.create(function(func, ...)
local args = { ... }
while (func) do
func, args = coroutine.yield({ func(table.unpack(args)) })
end
end)
end
-- 公共函数
function CoroutinePool.get()
local co = table.remove(coroutinePool)
if co then
return co
else
return createCoroutine()
end
end
function CoroutinePool.release(co)
table.insert(coroutinePool, co)
end
function CoroutinePool.execute(func, ...)
local co = CoroutinePool.get()
local success, results = coroutine.resume(co, func, { ... })
if not success then
CoroutinePool.release(co)
error("Coroutine error: " .. tostring(results))
end
CoroutinePool.release(co)
return table.unpack(results)
end
return CoroutinePool