[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [Libevent-users] async writes for bufferevent_write/bufferevent_write_buffer?




On Jul 18, 2013, at 8:30 PM, J. Scott Dorr wrote:


On Jul 18, 2013, at 10:57 AM, Mark Ellzey <mthomas@xxxxxxxxxx> wrote:

On Thu, Jul 18, 2013 at 10:52:06AM -0600, J. Scott Dorr wrote:

On Jul 18, 2013, at 9:59 AM, Mark Ellzey <mthomas@xxxxxxxxxx> wrote:

A little about deferred callbacks:

When you do something like bufferevent_write(), the actual underlying
protocol write is not executed immediately; it is queued up to be run in
the next iteration of the event loop. So if you do a sleep() in your
callback, you will not drop back to the main loop until you return.
Though even without the sleep, the write will not be done until the next
loop.

This was my expectation, but the fact that the client sees the echo'd hello before the sleep() finishes strongly suggests that the write is happening before going back to the event loop.
The sleep() is only there to help me visualize the flow and the order in which things take place.


Wait, so you see the write being done immediately? How is this not async?


The write is happening immediately when I call bufferevent_write().  It's not being queued up for the event loop.  It's happening synchronously in the context of the read handler that I'm currently in.  Instead of:

  1. enter read handler
  2. do read handler stuff
  3. queue up write() for later event loop iteration
  4. exit read handler
  5. go back to event loop
  6. write occurs
  7. client sees the data

I see:

  1. enter read handler
  2. do read handler stuff
  3. execute write() back to client which succeeds in line

write() is asynchronous; your data is copied to a kernel buffer immediately, and will be sent later.

  1. client sees the data
  1. exit read handler
  1. go back to event loop

Like I said, I can work around this and force the write to occur in the next iteration of the event loop by using a 0 second timer event, I just wanted to make sure I wasn't missing something.

Calling write on non-blocking socket will never block and you do not need to work around it. If the kernel does not like to copy your data when you call write, the call will fail with EAGAIN. All this is handled for you by bufferevent.