如何使用select或epoll使LuaJIT非阻塞?

huangapple go评论89阅读模式
英文:

How can I make LuaJIT non-blocking with select or epoll?

问题

我正在使用LuaJIT的ffi来调用epoll C库。然而,当没有事件发生时,epoll会阻塞,而我的软件需要在此期间执行其他任务。在C语言中,我知道可以在单独的线程中执行epoll,但LuaJIT不支持多线程。

以下是我的LuaJIT代码:

  local ctx = ffi.new_tcp("0.0.0.0", 5555)
  local server_socket = ffi.tcp_listen(ctx)
  local epoll_fd = ffi.C.epoll_create1(0)
  --.....
  --.....
  local nfds = ffi.C.epoll_wait(epoll_fd, events, NB_CONNECTION, -1)
-- 在这里会被阻塞,无法执行其他任务。

我该如何解决这个问题?

我该如何使用select或epoll使LuaJIT非阻塞?

英文:

I'm using LuaJIT's ffi to call the epoll C library. However, epoll blocks when there are no events, and my software needs to perform other tasks at that time. In C, I know I can execute epoll in a separate thread, but LuaJIT is not thread-safe.

Here's my luajit code:

  local ctx = ffi.new_tcp("0.0.0.0", 5555)
  local server_socket = ffi.tcp_listen(ctx)
  local epoll_fd = ffi.C.epoll_create1(0)
  --.....
  --.....
  local nfds = ffi.C.epoll_wait(epoll_fd, events, NB_CONNECTION, -1)
-- This is where it gets blocked and cannot execute other tasks.`

How can I solve this problem?

How can I make LuaJIT non-blocking with select or epoll?

答案1

得分: 1

根据epoll_wait man页面的文档,它的最后一个参数是一个超时时间,在此时间之后,它将停止阻塞并返回。传入的值为-1,即你传入的值,意味着“永久阻塞”,因此你的程序将永远阻塞。为了避免阻塞并简单地轮询更新,请传入0,或者传入一个以毫秒为单位的等待时间。

单线程的异步系统通常会在有待处理任务时轮询事件,如果没有任务,则会阻塞。

英文:

As documented in the epoll_wait man page, the last argument to it is a timeout, after which it will stop blocking and return. A value of -1 - the value you pass in - means "block forever", so your program blocks forever. To avoid blocking and simply poll for updates, pass in 0 instead, or pass in an amount of time in milliseconds to wait.

Single-threaded async systems usually will poll for events if there are pending tasks that it could be running instead and block if there aren't.

huangapple
  • 本文由 发表于 2023年7月27日 14:28:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定