matrixj之路

天阶夜色凉如水,卧看牵牛织女星。

hive源码之新建一个coroutine

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

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

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

 这个函数会用

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

把lua源文件加载进来

lua_pcall(L, 000)

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

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

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

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

 

3.scheduler_starttask(lua_State *L)

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

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

 

ps:"message_queue" "cell_pointer"是与L绑定的

posted on 2013-09-10 11:57  matrixj  阅读(231)  评论(0编辑  收藏  举报

导航