skynet服務之協程的威力
????接上一篇分析《skynet服務之launcher》,本篇我們繼續來分析一下lua中的協程如何與服務有機結合的,關於lua中協程的解釋參見本文《lua中協程的理解》;
上一篇分析到,當一個lua服務收到消息後,在lua層,最終會執行到raw_dispatch_message函數,代碼如下:
local
function raw_dispatch_message(prototype, msg, sz, session, source)
????-- skynet.PTYPE_RESPONSE = 1, read skynet.h
????if prototype ==
1
then
????????local co = session_id_coroutine[session]
????????if co ==
"BREAK"
then
????????????session_id_coroutine[session]
=
nil
????????elseif co ==
nil
????????????unknown_response(session, source, msg, sz)
????????else
????????????session_id_coroutine[session]
=
nil
????????????suspend(co, coroutine_resume(
????????end
????else
????????local p = proto[prototype]
????????if p ==
nil
then
????????????if session ~=
0
then
????????????????c.send(source, skynet.PTYPE_ERROR, session,
"")
????????????else
????????????????unknown_request(session, source, msg, sz, prototype)
????????????end
????????????return
????????end
????????local f = p.dispatch
????????if f then
????????????local ref = watching_service[source]
????????????if ref then
????????????????watching_service[source]
= ref +
1
????????????else
????????????????watching_service[source]
=
1
????????????end
????????????local co = co_create(f)
????????????session_coroutine_id[co]
= session
????????????session_coroutine_address[co]
= source
????????????suspend(co, coroutine_resume(co, session,source, p.unpack(msg,sz)))
????????elseif session ~=
0
then
????????????c.send(source, skynet.PTYPE_ERROR, session,
"")
????????else
????????????unknown_request(session, source, msg, sz, proto[prototype].name)