* Use independent thread for callback

* bugfix: use new cb_ctx when changing callback
This commit is contained in:
云风
2022-04-12 11:11:08 +08:00
committed by GitHub
parent 0ddd938400
commit e37eb3cba0

View File

@@ -46,18 +46,16 @@ traceback (lua_State *L) {
return 1; return 1;
} }
struct callback_context {
lua_State *L;
};
static int static int
_cb(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) { _cb(struct skynet_context * context, void * ud, int type, int session, uint32_t source, const void * msg, size_t sz) {
lua_State *L = ud; struct callback_context *cb_ctx = (struct callback_context *)ud;
lua_State *L = cb_ctx->L;
int trace = 1; int trace = 1;
int r; int r;
int top = lua_gettop(L);
if (top == 0) {
lua_pushcfunction(L, traceback);
lua_rawgetp(L, LUA_REGISTRYINDEX, _cb);
} else {
assert(top == 2);
}
lua_pushvalue(L,2); lua_pushvalue(L,2);
lua_pushinteger(L, type); lua_pushinteger(L, type);
@@ -102,17 +100,17 @@ lcallback(lua_State *L) {
int forward = lua_toboolean(L, 2); int forward = lua_toboolean(L, 2);
luaL_checktype(L,1,LUA_TFUNCTION); luaL_checktype(L,1,LUA_TFUNCTION);
lua_settop(L,1); lua_settop(L,1);
lua_rawsetp(L, LUA_REGISTRYINDEX, _cb); struct callback_context *cb_ctx = (struct callback_context *)lua_newuserdata(L, sizeof(*cb_ctx));
cb_ctx->L = lua_newthread(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD); lua_pushcfunction(cb_ctx->L, traceback);
lua_State *gL = lua_tothread(L,-1); lua_setuservalue(L, -2);
// reload callback function, See _cb() lua_setfield(L, LUA_REGISTRYINDEX, "callback_context");
lua_settop(gL, 0); lua_xmove(L, cb_ctx->L, 1);
if (forward) { if (forward) {
skynet_callback(context, gL, forward_cb); skynet_callback(context, cb_ctx, forward_cb);
} else { } else {
skynet_callback(context, gL, _cb); skynet_callback(context, cb_ctx, _cb);
} }
return 0; return 0;