Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

100% CPU usage with libev

Tags:

c

libev

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?

like image 368
elhadi dp ıpɐɥןǝ Avatar asked May 06 '26 05:05

elhadi dp ıpɐɥןǝ


1 Answers

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 */
}
like image 162
elhadi dp ıpɐɥןǝ Avatar answered May 10 '26 19:05

elhadi dp ıpɐɥןǝ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!