这个想法相当简单。首先,创建一个新线程。
lua_State *pThread = lua_newthread(L);
此函数还将该线程推送到L。下一步是将你的线程函数放到pThread 上。鉴于此时堆栈上有一个 Lua 函数,下一步就是将该函数转移到 pThread 堆栈。
有一个专门用于在线程之间传输值的函数:lua_xmove。但是,它只传输堆栈的顶部元素。所以你需要将 Lua 函数从它在L 的堆栈中的位置复制到L 的堆栈的顶部。然后lua_xmove 到新堆栈。
lua_pushvalue(L, #); //Where # is the index in the stack where the function is.
//Remember that lua_newthread pushed a value on the stack, so compensate for that.
lua_xmove(L, pThread, 1); //Moves the function to the top of the new stack.
请记住 lua_xmove 移动值,这会将其从 L 中删除。所以lua_pushvalue 推送值,lua_xmove 弹出它。所以栈顶又是pThread代表的lua_State。
之后,将您需要发送的所有参数推送到函数(显然为零),然后恢复它。
lua_resume(pThread, 0, 0);
总码:
lua_State *pThread = lua_newthread(L);
lua_pushvalue(L, #); //Where # is the index in the stack where the function is.
//Remember that lua_newthread pushed a value on the stack, so compensate for that.
lua_xmove(L, pThread, 1); //Moves the function to the top of the new stack.
lua_resume(pThread, 0, 0);
Lua 线程(无论是在 Lua 中创建还是在 C API 中创建的)是一个 Lua 值,就像一个表、用户数据、字符串等。因此,它受到垃圾回收的影响。当 Lua 检测到没有更多对该值的引用时,它将被收集。
记住:lua_newthread 将线程推入原始堆栈。您可以将其复制到注册表、全局环境或您打算永久驻留该线程的任何位置。仅仅保留一个指向它生成的lua_State 的指针不会确保线程保持活动状态。