skynet服务的本质与缺陷

skynet服务的设计

统观整篇文章,不难发现:

每个skynet服务都是一个lua state,也就是一个lua虚拟机实例。而且,每个服务都是隔离的,各自使用自己独立的内存空间,服务之间通过发消息来完成数据交换。

架构图如下:


图片取自spartan1的skynet任务调度分析

lua state本身没有多线程支持的,为了实现cpu的摊分,skynet实现上在一个线程运行多个lua state实例。而同一时间下,调度线程只运行一个服务实例。为了提高系统的并发性,skynet会启动一定数量的调度线程。同时,为了提高服务的并发性,就利用lua协程并发处理。

所以,skynet的并发性有3点:

1、多个调度线程并发
2、lua协程并发处理
3、服务调度的切换


skynet服务的设计基于Actor模型。有两个特点:

1. 每个Actor依次处理收到的消息
2. 不同的Actor可同时处理各自的消息

实现上,cpu会按照一定规则分摊给每个Actor,每个Actor不会独占cpu,在处理一定数量消息后主动让出cpu,给其他进程处理消息。



skynet服务的缺陷


并发问题

这要从skynet一个服务霸占调度器的极端例子说起。

下面给出两个lua代码 main.lua 和 simpledb.lua,和一个配置文件 config 

  1. -- main.lua  
  2.   
  3. local skynet = require "skynet"  
  4.   
  5. skynet.start(function()  
  6.     print("Server start")  
  7.     skynet.newservice("simpledb")  
  8.   
  9.     -- 发消息给simpledb服务  
  10.     skynet.send("SIMPLEDB", "lua", "TEST")  
  11.     -- 死循环占据cpu  
  12.     local i = 0  
  13.     while true do  
  14.         i = i>100000000 and 0 or i+1  
  15.         if i==0 then  
  16.             print("I'm working")   
  17.         end  
  18.     end  
  19.     skynet.exit()  
  20. end)  
-- main.lua

local skynet = require "skynet"

skynet.start(function()
	print("Server start")
	skynet.newservice("simpledb")

	-- 发消息给simpledb服务
	skynet.send("SIMPLEDB", "lua", "TEST")
	-- 死循环占据cpu
	local i = 0
	while true do
		i = i>100000000 and 0 or i+1
		if i==0 then
			print("I'm working") 
		end
	end
	skynet.exit()
end)
  1. -- simpledb.lua  
  2.   
  3. local skynet = require "skynet"  
  4. require "skynet.manager"    -- import skynet.register  
  5. local db = {}  
  6.   
  7. local command = {}  
  8.   
  9. function command.TEST()  
  10.     print("Simpledb test")  
  11.     return true  
  12. end  
  13.   
  14. skynet.start(function()  
  15.     print("Simpledb start")  
  16.     skynet.dispatch("lua", function(session, address, cmd, ...)  
  17.         local f = command[string.upper(cmd)]  
  18.         if f then  
  19.             skynet.ret(skynet.pack(f(...)))  
  20.         else  
  21.             error(string.format("Unknown command %s", tostring(cmd)))  
  22.         end  
  23.     end)  
  24.     skynet.register "SIMPLEDB"  
  25. end)  
-- simpledb.lua

local skynet = require "skynet"
require "skynet.manager"	-- import skynet.register
local db = {}

local command = {}

function command.TEST()
	print("Simpledb test")
	return true
end

skynet.start(function()
	print("Simpledb start")
	skynet.dispatch("lua", function(session, address, cmd, ...)
		local f = command[string.upper(cmd)]
		if f then
			skynet.ret(skynet.pack(f(...)))
		else
			error(string.format("Unknown command %s", tostring(cmd)))
		end
	end)
	skynet.register "SIMPLEDB"
end)
配置文件 config
  1. root = "./"  
  2. thread = 1  
  3. logger = nil  
  4. logpath = "."  
  5. harbor = 1  
  6. address = "127.0.0.1:2526"  
  7. master = "127.0.0.1:2013"  
  8. start = "main"  
  9. bootstrap = "snlua bootstrap"  
  10. standalone = "0.0.0.0:2013"  
  11. luaservice = root.."service/?.lua;"..root.."test/?.lua;"..root.."examples/?.lua"  
  12. lualoader = "lualib/loader.lua"  
  13. snax = root.."examples/?.lua;"..root.."test/?.lua"  
  14. cpath = root.."cservice/?.so"  
root = "./"
thread = 1
logger = nil
logpath = "."
harbor = 1
address = "127.0.0.1:2526"
master = "127.0.0.1:2013"
start = "main"
bootstrap = "snlua bootstrap"
standalone = "0.0.0.0:2013"
luaservice = root.."service/?.lua;"..root.."test/?.lua;"..root.."examples/?.lua"
lualoader = "lualib/loader.lua"
snax = root.."examples/?.lua;"..root.."test/?.lua"
cpath = root.."cservice/?.so"

注意了,这里特地把 thread 设置为1,表示只启动一个调度线程。

现在,启动skynet执行我们的例子,结果如下:
[root@local skynet]# ./skynet config
[:01000001] LAUNCH logger 
[:01000002] LAUNCH snlua bootstrap
[:01000003] LAUNCH snlua launcher
[:01000004] LAUNCH snlua cmaster
[:01000004] master listen socket 0.0.0.0:2013
[:01000005] LAUNCH snlua cslave
[:01000005] slave connect to master 127.0.0.1:2013
[:01000004] connect from 127.0.0.1:41589 4
[:01000006] LAUNCH harbor 1 16777221
[:01000004] Harbor 1 (fd=4) report 127.0.0.1:2526
[:01000005] Waiting for 0 harbors
[:01000005] Shakehand ready
[:01000007] LAUNCH snlua datacenterd
[:01000008] LAUNCH snlua service_mgr
[:01000009] LAUNCH snlua main
Server start
[:0100000a] LAUNCH snlua simpledb
Simpledb start
I'm working
I'm working
I'm working
可以看出,simpledb 没有机会处理TEST消息,一直是main模块占据着cpu。


为什么会出现这个情况?

这和skynet的调度机制有关。skynet使用全局队列保存了要调度的服务,调度算法是先来先服务。如果某个服务有新消息,就把这个服务加到调度队列中,然后等待调度线程调度。而skynet服务的调度切换依赖于协程的挂起,如果当前调度的服务没有主动挂起或退出,就会一直执行,不调度其他服务了。

这种机制的好处就是实现简单,有利于长作业,上下文切换较少,缺点就是并发效率低,而且像这种长作业的服务超过调度线程数量,就可能导致其他服务饿死。


内存隐患

细心的同学会发现,在服务处理新消息时,是通过创建新协程来处理的(见co_create),虽然协程会被重复利用,但在当前版本下,这种不断创建协程来消息的方式本身存在不稳定因素:
1、协程只增加不减少,意味过了某个并发高峰后内存不会降下来。
2、创建协程也有一定开销,容易触发GC,也占用内存,协程的数量规模不容易控制
3、如果解决第1点,最槽糕的情况是,不断要创建协程,不断要销毁协程,频繁触发gc

这里有一个极端的例子:

如果服务a不断给服务b发消息,但服务b的处理过程存在长时间挂起,这样,对于服务a发来的消息,服务b会不断创建协程去处理,就导致内存被大量占用的情况出现。

但是skynet也提供办法解决这个问题,方法是主动调用GC:

  1. skynet.send(service,"debug","GC")  
skynet.send(service,"debug","GC")

另外,有兴趣的同学,不妨看下实现代码:

  1. -- debug.lua  
  2.   
  3. return function (skynet, export)  
  4.   
  5. -- 处理 GC 消息  
  6. function dbgcmd.GC()    
  7.     export.clear()  -- export 是 skynet.debug 的传入参数  
  8.     collectgarbage "collect"  -- 执行GC  
  9. end  
  10.   
  11. local function _debug_dispatch(session, address, cmd, ...)  
  12.     local f = (dbgcmd or init_dbgcmd())[cmd]    -- lazy init dbgcmd  
  13.     f(...)  
  14. end  
  15.   
  16. skynet.register_protocol {  
  17.     name = "debug",  -- 注册处理服务收到的 "debug" 消息  
  18.     id = assert(skynet.PTYPE_DEBUG),  
  19.     pack = assert(skynet.pack),  
  20.     unpack = assert(skynet.unpack),  
  21.     dispatch = _debug_dispatch,  
  22. }  
  23. end  
-- debug.lua

return function (skynet, export)

-- 处理 GC 消息
function dbgcmd.GC()  
	export.clear()  -- export 是 skynet.debug 的传入参数
	collectgarbage "collect"  -- 执行GC
end

local function _debug_dispatch(session, address, cmd, ...)
	local f = (dbgcmd or init_dbgcmd())[cmd]	-- lazy init dbgcmd
	f(...)
end

skynet.register_protocol {
	name = "debug",  -- 注册处理服务收到的 "debug" 消息
	id = assert(skynet.PTYPE_DEBUG),
	pack = assert(skynet.pack),
	unpack = assert(skynet.unpack),
	dispatch = _debug_dispatch,
}
end

而什么时候调用了 skynet.debug 呢?看这里

  1. -- skynet.lua  
  2.   
  3. local function clear_pool()  
  4.     coroutine_pool = {} -- 清空协程的引用  
  5. end  
  6.   
  7. -- debug设置回调处理函数  
  8. local debug = require "skynet.debug"  
  9. debug(skynet, {  
  10.     dispatch = skynet.dispatch_message,  
  11.     clear = clear_pool,  
  12.     suspend = suspend,  
  13. })  
-- skynet.lua

local function clear_pool()
	coroutine_pool = {} -- 清空协程的引用
end

-- debug设置回调处理函数
local debug = require "skynet.debug"
debug(skynet, {
	dispatch = skynet.dispatch_message,
	clear = clear_pool,
	suspend = suspend,
})

就是说,但给服务发送GC消息时,就会清空协程池,随后执行底层GC接口。这样,不再有内容引用到这个协程,所以,协程会在GC时被清理。

至于协程只是挂起没有结束,为什么会被清理?

因为从协程池移走后,那些协程就变成了不可达的协程了,没有方法能 coroutine.resume 激活他们了,所以就会被gc掉。


同步问题

同步也是skynet存在的问题,当一个服务call其他服务时,当前协程会挂起,但是这个服务还可以接受并处理其他消息。如果多个协程改到同一个数据,你不做同步处理就无法确定这个数据会是多少。

这样的例子特别常见,比如,服务正当处理玩家login请求,刚好遇到call挂起,这时候又有新的请求到来,比如logout,服务就会转去处理logout消息。那玩家究竟是login,还是logout?

当然,同步问题也容易解决,加多一个state的标识和一个协程列表,操作执行时,将state置doing,其他协程判断state=doing时就将自己加到协程列表,然后 skynet.wait。在操作执行完后,重置state,然后遍历协程列表依次 skynet.wakeup(co) ,最后将协程列表置空。

参考:http://blog.csdn.net/mycwq/article/details/47379277

猜你喜欢

转载自blog.csdn.net/u010144805/article/details/80596478