hive源码之新建一个coroutine

时间:2023-03-09 15:37:21
hive源码之新建一个coroutine

最近由于项目需要读了一下云风老大的hive项目代码,因为对lua只有熟悉的水平,下面的东西必然多多错误:),只为记录。

 lua_State *sL = schedule_newtask(L);
struct cell *c = cell_new(SL, filname);//filename是要加载的lua文件,里面有相关的启动方法,这个函数接下来再说;
...
cell_touserdata(L, lua_upvalueindex(), c);//下面说到
scheduler_starttask(sL);//把sL的cell挂到message_queue上去,详情继续看下面
//至此,启动一个coroutine完成

1.cell_new(lua_State *L, const char *filename)

这个函数会用

 cell_new(...) //创建一个cell结构体 c,
c->L = L // 把L挂到c上去
//然后调用cell_touserdata返回(或新建)一个cell_ud结构体,然后把它放在stack top,将其设置为cell.lib
//(这个表由cell.c模块产生)上key=="self"的value,
...
hive_getenv(L, "system_cell");//得到system cell,然后用`cell_touserdata`把返回的cell_ud设置为cell.lib上key=="system"的value
...
//把cell_new出来的 c 设置为全局表LUA_RESTRYINDEX上KEY==“cell_pointer"的value
//开始加载cell的lua源文件(filename 是使用 package.searchpath(...)搜出来的)
luaL_loadfile(L, filename)

把lua源文件加载进来

lua_pcall(L, , ,)

运行,之后又会压入5个值作为lcallback的upvalue。

2.cell_touserdata(lua_State *L, int index, struct cell *c)

这个函数会先判断L 中 index处的c存不存在 userdata,如果不存在则:

 struct cell_ud * cud = lua_newuserdata(L, sizeof(*cud));//新建一个
...//给 c 的ref引用加1
...//给 cud 设置metatable,设置 '__gc' '__tostring' 'CELL_TAG'等
lua_rawsetp(L, index, c);//将cud设置为index处的value

3.scheduler_starttask(lua_State *L)

先获得L的"message_queue" 和 "cell_pointer",然后把 cell放到 message_queue上去,代码如下:

 struct cell_ud * cud = lua_newuserdata(L, sizeof(*cud));//新建一个
...//给 c 的ref引用加1
...//给 cud 设置metatable,设置 '__gc' '__tostring' 'CELL_TAG'等
lua_rawsetp(L, index, c);//将cud设置为index处的value
ps:"message_queue" "cell_pointer"是与L绑定的