3

I have a tcp server which uses libev as an event loop; for new accepted sockets i set:

 ev_io_init(&conn->io, tcp_conn_on_event_cb, conn->fd, EV_READ | EV_WRITE);

when a new connection is comming, my server consumes whole the CPU cycles, i have 100% CPU usage. my program calls all the time the callback tcp_conn_on_event_cb with revents set as EV_WRITE

static void tcp_conn_on_event_cb(ev_loop_t *loop, ev_io *ev, int revents)

when i make

strace mybinary

i've this:

epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
epoll_wait(4, {{EPOLLOUT, {u32=7, u64=4294967303}}}, 64, 59743) = 1
                           ....

is there a solution fo this problem please?

elhadi dp ıpɐɥןǝ
  • 4,763
  • 2
  • 30
  • 34

1 Answers1

4

I've found a solution, For those who are interested in this question:

when accepting a new socket, do not call ev_io_init with EV_WRITE, call it only with EV_READ.

ev_io_init(&conn->io, tcp_conn_on_event_cb, conn->fd, EV_READ);

in the callback, if you have a data to write (to the socket), you can use ev_feed_fd_event

static void tcp_conn_on_event_cb(ev_loop_t *loop, ev_io *ev, int revents)
{
      ....

    if (revents | EV_WRITE) {
         /* write your data here */
    }

    if (data_is_ready()) {
        ev_feed_fd_event(loop, conn->fd, EV_WRITE | revents);
        return;
    }

    /* do other job */
}
elhadi dp ıpɐɥןǝ
  • 4,763
  • 2
  • 30
  • 34
  • 1
    Thanks. This helped me. I was behind timers causing high CPU. But this solved my issue. I was setting both EV_READ and EV_WRITE for new socket. – sunil Dec 04 '17 at 05:54