由于skynet服务有重入问题,所以找到了一个skynet queue方法。
简单用法,假设test为在服务中需要顺序执行的函数。只要把一个函数往queue扔就行了。
local function test()
print("hello world")
end
local queue = require "skynet.queue"
queue(test)
翻了一下源代码,实现是用一个闭包函数达到目的。整体思路就是记录下current thread,判断current thread是否和local thread相等,只有两者相等才执行。
以下是源码片段:
function skynet.queue()
local current_thread
local ref = 0
local thread_queue = {}
return function(f, ...)
local thread = coroutine.running()
if current_thread and current_thread ~= thread then
table.insert(thread_queue, thread)
skynet.wait()
assert(ref == 0) -- current_thread == thread
end
current_thread = thread
ref = ref + 1
local ok, err = xpcall(f, traceback, ...)
ref = ref - 1
if ref == 0 then
current_thread = table.remove(thread_queue,1)
if current_thread then
skynet.wakeup(current_thread)
end
end
assert(ok,err)
end
end