|
Boost Users : |
Subject: Re: [Boost-users] Using boost::asio::async_write to stream out data
From: Michael Caisse (boost_at_[hidden])
Date: 2009-07-17 14:09:51
Hello Alex -
Alex Black wrote:
> My app writes out a large amount of data to a socket, in a loop, in
> pieces, say 8kb at a time.
>
> I'd like to switch from using Socket::send to use asio::async_write. At
> a high level, what do I need to do? From my reading, I think I need to:
>
> 1. Call async_write instead of send
>
> 2. Ensure that my buffers have the correct lifetime
> - today since my writes are synchronous I re-use the same buffer over
> and over again
> - so instead, should I make a new buffer for each write? Whats a good
> way to ensure the buffer has the correct lifetime, e.g. how do I delete
> it once its been written out?
>
If you are newing off some space in the heap you could just use a
queue of shared_ptr to your data and let the reference counting take
care of it for you. In your completion routine for the write simply
pop off the entry for the buffer just written and then the buffer would
be deleted.
You may find that using a pool technique will be much better depending
on your application. The same concept would hold, the memory would be
returned to the pool at the completion routine for the write.
> 3. I understand I can't call async_write again before the first one has
> been completed (since I don't want my 8kb chunks interleaved), so should
> I maintain a queue of buffers waiting to go out?
>
Correct. You need to check your queue in the completion routine and kick off
another async_write if required. I typically use a std::deque to handle this for
me. Sometimes just a std::deque< std::string > depending on the application.
> Then in my handle_write method should I check the queue, if at least one
> buffer is in the queue then I should start a new async_write?
>
Exactly.
michael
-- ---------------------------------- Michael Caisse Object Modeling Designs www.objectmodelingdesigns.com
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net