如何通过多个国家的Lua(多线程)之间的数据? [英] How to pass data between multiple Lua State(multi-thread)?
问题描述
我发起的Redis连接池的 redis.lua 的,由C调用,我得到了一个 redis_lua_state
,这Lua的状态是全球发起一次和其他线程只的从它那里得到的
虽然有自带一个HTTP请求(工作线程),我需要获取从 redis_lua_state
,那么新的另一个Lua的状态来加载其他的Lua脚本Redis的连接,而这些脚本将使用Redis的连接与Redis的沟通,如何做到这一点?或如何设计我的Lua脚本,使之简单?
code样品:</ STRONG>
/ *在主线程,给init Redis的池连接* /
lua_State * g_ls = NULL;
lua_State * init_redis_pool(无效){
INT RET = 0;
g_ls = luaL_newstate();
lua_State 1!= g_ls; luaL_openlibs(LS);
RET = luaL_loadfile(LSredis.lua);
为const char *走错了路。
(无效)错误; / * preLOAD * /
RET = lua_pcall(LS,0,0,0); lua_getglobal(LSinit_redis_pool);
RET = lua_pcall(LS,0,0,0); 返回LS;
} / *工作线程* /
INT工人(){
...
lua_State 1!= luaL_newstate();
RET = luaL_loadfile(LSrun.lua); / *如何来从g_ls数据? * /
...
lua_getglobal(LS,运行)
RET = lua_pcall(LS,0,0,0) lua_close(LS);
...
返回0;
}
如果你的Lua状态是独立的,那么有没有办法做到这一点。你的工作线程将初始化的Redis连接的和的做就可以处理。
I initiate Redis connection pool in redis.lua, by calling from C, I got a redis_lua_state
, this Lua state is global initiated once and other thread only get from it.
While there comes a HTTP request(worker thread), I need to fetch a redis connection from redis_lua_state
, then new another Lua state to load other Lua script, and these scripts will use this redis connection to communicate with Redis, how to do this? Or how to design my Lua scripts to make it simple?
Code Sample:
/* on main thread, to init redis pool connection */
lua_State *g_ls = NULL;
lua_State *init_redis_pool(void) {
int ret = 0;
g_ls = luaL_newstate();
lua_State *ls = g_ls;
luaL_openlibs(ls);
ret = luaL_loadfile(ls, "redis.lua");
const char *err;
(void)err;
/* preload */
ret = lua_pcall(ls, 0, 0, 0);
lua_getglobal(ls, "init_redis_pool");
ret = lua_pcall(ls, 0, 0, 0);
return ls;
}
/* worker thread */
int worker() {
...
lua_State *ls = luaL_newstate();
ret = luaL_loadfile(ls, "run.lua");
/* How to fetch data from g_ls? */
...
lua_getglobal(ls, "run")
ret = lua_pcall(ls, 0, 0, 0)
lua_close(ls);
...
return 0;
}
If your Lua states are separate, then there's no way to do this. Your worker thread will have to initialize the Redis connection and do processing on it.
这篇关于如何通过多个国家的Lua(多线程)之间的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!