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

73 Views Asked by At

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

There are 1 best solutions below

0
Colonel Thirty Two On

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.