Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] async_read and 100% CPU
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-06-30 16:04:31


> On Tue, Jun 30, 2009 at 2:24 PM, Etienne Philip Pretorius<icewolfhunter_at_[hidden]> wrote:
>> Zachary Turner wrote:
>> What is contained inside your buffer object?  If your buffer has a
>> size of 0, then this seems like it would cause the problem.
>>
> yip, it has a size of 0. I hoped that the async receive would just increase
> the size of the vector as it puts the contents into it, but that is not
> happening.

I'm 99% sure this is your problem. I haven't used asio with sockets,
but I have used it with other types of input sources. It doesn't know
how much data to read unless you tell it. The way you tell it is by
giving it a buffer whose size is how much data you want to read. That
means that allocation / deletion of the buffer is also your
responsibility.

boost::asio::const_buffer and boost::asio::mutable_buffer have no
ownership over the memory contained in these buffers. It seems like
this makes the library a little less intuitive at first, I struggled
for quite a while with buffer management in my own project, but in the
end it is this way to help you. Otherwise there would be excessive
copying and allocation. mutable_buffer and const_buffer are just very
thin wrappers over a chunk of memory. So you have to allocate a
buffer up front that contains enough memory for whatever it is you're
trying to read. Then you pass that to async_receive and it should
work.

                   const size_t expected = 4096;
                   unsigned char* buf = new unsigned char[expected];
                   boost::asio::mutable_buffer(buf, expected);

                   socket.async_receive(
                       boost::asio::buffer(buffer),
                       boost::bind(
                           &client::handle_read,
                           this,
                           boost::asio::placeholders::error,
                           boost::asio::placeholders::bytes_transferred

Now in your handler you will either need to free this buffer, release
it to some cache, or whatever else you want to do with it.


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