0

In libevent I've added the following code:

while (run) {
  event_base_loop(base, EVLOOP_NONBLOCK | EVLOOP_ONCE);
}

If I compare this to the following:

event_base_dispatch(base);

Are these two statements equal?

name5566
  • 91
  • 2
  • 5

1 Answers1

1

No, the event_base_dispatch(base) call is equivalent to event_base_loop(base, 0), which means that it will neither stop after the first batch of events (like event_base_loop with EVLOOP_ONCE does) nor return immediately if there is no event ready (like event_base_loop with EVLOOP_NONBLOCK does).

You may want to read the great book on libevent written by Nick Mathewson : http://www.wangafu.net/~nickm/libevent-book/Ref3_eventloop.html

brokenfoot
  • 11,083
  • 10
  • 59
  • 80
Remi Gacogne
  • 4,655
  • 1
  • 18
  • 22
  • Thanks Remi. I want to do something in the event loop, so I try to use `while (run) event_base_loop(base, EVLOOP_NONBLOCK | EVLOOP_ONCE)` instead of `event_base_dispatch(base)`. Does this have a efficiency problem or other risks? – name5566 Mar 13 '13 at 01:47
  • Looping on event_base_loop(base, EVLOOP_NONBLOCK | EVLOOP_ONCE) is slightly less efficient that simply doing event_base_dispatch(). Can I ask what you are trying to do ? Have you tried doing it with a timer event, or using event_base_loopbreak() ? – Remi Gacogne Mar 13 '13 at 09:35
  • I have a network thread and a user thread, the network thread call `event_base_loop` for event loop (detail: `while(run) { event_loop; MyUpdate(); }`). I try to call the function `bufferevent_socket_connect` in user thread, but it's not work (not thread safe?). So, I do this: user thread: push a connection request to a request buffer; network thread: 1. looping on the request buffer 2. get a connection request 3. call buffervent_socket_connect to connect. – name5566 Mar 14 '13 at 07:02
  • I don't see why you need to get out of the loop ? Regarding libevent and threads, see http://www.wangafu.net/~nickm/libevent-book/Ref1_libsetup.html#_locks_and_threading – Remi Gacogne Mar 14 '13 at 13:33
  • Libevent isn't actually thread safe in my experience. Some APIs don't work correct in multithread environment. The worst thing is that calling `bufferevent_free` from an other thread will deadlock ([link](http://archives.seul.org/libevent/users/Aug-2012/msg00003.html)). So I try to call the bufferevent APIs in the network thread, the user thread just send some request to the network thread instread of calling the bufferevent API directly. I need to get out of the loop, and process the user thread request. – name5566 Mar 15 '13 at 02:25