lua中的user_t对象每个实例拥有两个主要数据, a. request_cache,在user未初始化完成时该uid的请求将被缓存起来(我们将请求封装成function)。 b. coroutine ,该协程尝试将request_cache中的所有请求执行完毕,当出现如下情况该协程为挂起自己 (1)request_cache 为空,挂起等待新的请求 (2)需要执行mysql时挂起,等待mysql执行完毕被唤醒。
user_t = {} user_t.__index = user_t function() local funjc = function()print("TODO exe all request in request_cache") end local ret = { ["request_cache"] = {}, ["coroutine_obj"] = coroutine.create(funjc), } setmetatable(ret, self) return ret end ```
2. C++ 封装异步调用Mysql的接口,注册接口到LUA 1. future_t 用于LUA和C++传递数据
function(uid_) local ret = { ["uid"] = uid_, ["request_cache"] = {}, ["coroutine_obj"] = true, ["runing_flag"] = true, } setmetatable(ret, self)
local func = function() whiletrue == runing_flag if0 == #ret.request_cache then coroutine.yield() else local todo_func = ret.request_cache[1] local tmp = {} for k = 2, #ret.request_cache do table.insert(tmp, ret.request_cache[k]) end ret.request_cache = tmp todo_func() end end end ret.coroutine_obj = coroutine.create(func) return ret end
functionuser_t:init() local func = function() local future = future_t:new() async_load_data_from_db(future) coroutine.yield() print("user_t:init ok", self.uid, future:get_result()) future:delete() end table.insert(self.request_cache, func) coroutine.resume(self.coroutine_obj) end
functionuser_t:resume_routine() coroutine.resume(self.coroutine_obj) end
local test_user = user_t:new(1122334)
functionuser_login() return test_user:init() end
functionresume_routine() return test_user:resume_routine() end