如何暂停/恢复处理Lua命令

我正在编写一个客户端,它可以与多个服务器交流,并处理用户在stdin(标准输入)上的命令,最后使用Lua从文件中读取。服务器是一个自定义应用程序,因此我正在处理所有与C通信的代码,其中协议的所有代码都已经编写好了。这里是我现在的伪代码:

int main(int argc, char **argv) {
  /* 设置fd列表,变量等 */
  ...
  while (1) {
    /* 处理文件描述符列表以创建读/写fd集 */
    ...
    select(max, &read_fds, &write_fds, NULL, NULL);
    for each file descriptor {
      if (read fd is set) {
        read data into a buffer
        if (current fd is stdin)
          process_stdin()
        else if (current fd is from server connection)
          process_remote()
      }
      if (write fd is set) {
        write data on non-blocking fd
      }
    }
  }
}

int process_stdin() {
  luaL_loadbuffer(L, stdin_buffer, len, "stdin");
  lua_pcall(L, 0, 0, 0);
}

int process_remote() {
  parse buffer into message from remote system
  if message is complete, call Lua with either a new message notification or resume
}

所以问题来了:如果用户在stdin上输入类似wait_for_remote_message(xyz)的内容,我该如何停止在那一点,从lua_pcall中返回,并进入select循环等待更多数据?然后,process_remote如何从那一点恢复Lua命令?

我可以想象使用pthread的解决方案,但这感觉对于这个应用程序来说过于繁琐,并引入了很多额外的复杂性。

我还可以想象一种解决方案,其中while(1)/select循环移动到一个函数中,并且从wait_for_remote_message(xyz)返回到C并使用stdin添加到某种排除列表来调用此函数。

有更好的办法吗?

原文链接 https://stackoverflow.com/questions/6145059

点赞
stackoverflow用户618963
stackoverflow用户618963

这似乎是 Lua 协程的一个完美应用,你可以调用 yield 暂停执行,然后稍后恢复。

详细信息请查看 http://www.lua.org/pil/9.html

你可以这样做:

int process_stdin() {
    lua_State coroutine =  lua_newthread(L);

    luaL_loadbuffer(coroutine, stdin_buffer, len, "stdin");
    if (lua_resume(coroutine, 0) == LUA_YIELD) {
     // 将协程存储在某个全局位置
    }
}

int process_remote() {
    // 将缓冲区解析成来自远程系统的消息

    // 将消息推送到 Lua 栈上
    lua_resume(coroutine, 1);
}
2011-05-26 23:34:38