Lua 协程池

协程池

使用 Lua 协程模拟 Golang 的 go defer 编程模式 中介绍了 Lua 协程的使用,模仿 golang 封装了下

还可以做进一步的优化

原来的 go 函数是这样实现的:

lua 复制代码
function go(_co_task)
	local co = coroutine.create(function(_co_wrap)
        _co_task(_co_wrap)
        invoke_defer_handlers(_co_wrap, {ok=true}) -- 正常退出
    end)
    local cowrap = { co = co, defer_handlers = {} } ---@type co_wrap
    coroutine_resume(cowrap)
end

go一次,均coroutine.create创建一根协程

阅读了 skynet 相关使用协程的代码,发现 skynet 使用了协程池

因此可以借鉴过来

具体实现

引入协程池的类似代码如下:

lua 复制代码
---@type co_wrap[]
local coroutine_pool = setmetatable({}, { __mode = "kv" })
local coroutine_max_idle_num = 10 -- 协程池,最大空闲个数

function go(_co_task)
    local co_wrap_0 = table.remove(coroutine_pool) ---@type co_wrap
    if not co_wrap_0 then
        local co = coroutine.create(function()
            while true do
                local co_wrap_2, co_tesk_2 = coroutine.yield()
                co_tesk_2(co_wrap_2)
                invoke_defer_handlers(_co_wrap, {ok=true}) -- 正常退出
                co_tesk_2 = nil
                if #coroutine_pool < coroutine_max_idle_num then
                    coroutine_pool[#coroutine_pool + 1] = { co = co_wrap_2.co, defer_handlers = {} }
                    co_wrap_2 = nil
                else
                    co_wrap_2 = nil
                    return
                end
            end
        end)
        continue.resume(co)
        local co_wrap_1 = { co = co, defer_handlers = {} } ---@type co_wrap
        coroutine_resume(co_wrap_1, co_wrap_1, _co_task)
    else
        -- 复用协程
        coroutine_resume(co_wrap_0, co_wrap_0, _co_task)
    end
end
  • go 函数,pop coroutine_pool 队尾,如果不为空,则有协程可以复用;否则新建协程处理
  • 因为协程需要复用,因此需要解耦 _co_task ,可以通过 resume 传递过去
  • 还可以设置协程池大小。进而判断,压入 coroutine_pool 继续 yield 等待下个任务;还是直接结束本协程
相关推荐
小王不爱笑1324 分钟前
IO 模型
开发语言·python
知我Deja_Vu23 分钟前
【避坑指南】ConcurrentHashMap 并发计数优化实战
java·开发语言·python
AI+程序员在路上33 分钟前
CANopen 协议:介绍、调试命令与应用
linux·c语言·开发语言·网络
2401_8318249633 分钟前
基于C++的区块链实现
开发语言·c++·算法
m0_518019481 小时前
C++与机器学习框架
开发语言·c++·算法
ZTLJQ1 小时前
深入理解逻辑回归:从数学原理到实战应用
开发语言·python·机器学习
qq_417695051 小时前
C++中的代理模式高级应用
开发语言·c++·算法
波波0072 小时前
每日一题:.NET 中的“反射”是什么?
开发语言·.net
qq_461489332 小时前
C++与Qt图形开发
开发语言·c++·算法
Evand J3 小时前
【三维飞行器】RRT路径规划与TOA定位仿真系统,MATLAB例程,路径起终点、障碍物、TOA锚点等均可设置。附下载链接
开发语言·matlab·无人机·定位·rrt·toa·三维航迹规划