poold.lua 930 Bytes
--[[
	deque 为了减少锁竞争,尽量保证 a服务 push;b服务 pop
]]
local skynet = require "skynet"
local deque = require "deque"

local CMD = {}
local factory

local dead = 0
-- agent死亡,通知poold补充,当累计到5个agent时,马上生成5个agent放入poold中
-- 当然这里也可以写得更复杂,参考redis落地规则
function CMD.feed()
	dead = dead + 1
	if dead == 5 then
		dead = 0
		for i=1, 5 do
			factory:push(skynet.newservice("agent"))
		end
	end
end

-- 系统启动,生成count个agent放入双端队列中
function CMD.start(count)
	factory, addr = deque.new(count)

	for i=1, count do
		factory:push(skynet.newservice("agent"))
	end

	return addr
end

local function __init__()
	skynet.dispatch("lua", function (_, _, command, ...)
		local f = CMD[command]
		if command == "start" then
			skynet.ret(skynet.pack(f(...)))
			return
		end
		f(...)
	end)
end

skynet.start(__init__)