I think this is a concurrency problem, when in [2] you call read() from readHandler(), there could data in the socket waiting to be read, and the async_receive_from will fill the buffer before or at the same time you  create the szDatagram string.

That's why the read() funciton must be called only then you are done using the buffer, I'm pretty sure you can call read() before printing to cerr, but not before copying the buffer to the string szDatagram..

__________
Saludos!
     Juan



On Sat, Feb 16, 2013 at 3:24 PM, ustulation <ustulation@gmail.com> wrote:
By going through the doc. i understand that async completion handlers will be
called whenever io_service::run() reads posted events from the queue for
which the corresponding handlers were registered by us. Now if i have a
registered handler for some event (say async_wait() of deadline_timer) which
does something time consuming, then event loop (io_service::run()) does not
get a chance to read the event queue until the handler returns thus
preventing calls to other handlers for which events are queued. I've tested
this behaviour with timers and it works as expected. However i could not
understand the behaviour of  async_read_from() of udp::socket.

void A::read()
{
    udpSoc.async_receive_from(
            boost::asio::buffer(m_cRxData, 1024),
            m_endpoint,
            boost::bind(&A::readHandler, this, _1, _2)
            );
}

//////////////////////////////  <1> ///////////////////////////
void A::readHandler(......)
{
      std::string szDatagram(m_cRxData, bytesReceived);
      std::cerr << "Rxd Datagram: " << szDatagram << std::endl;

      read();

//............

}


//////////////////////////////  <2> ///////////////////////////
void A::readHandler(......)
{
      read();

      std::string szDatagram(m_cRxData, bytesReceived);
      std::cerr << "Rxd Datagram: " << szDatagram << std::endl;

//............

}

in above when 2 datagrams arrive simultaneously, readHandler <1> works fine
but <2> does not. In <1> std::cerr write 1st and 2nd Datagrams distinctly,
but in <2> data gets corrupted and std::cerr writes a string that would be
formed if the 1st datagram in it were overwritten by the 2nd datagram (ie.,
if 1st one was 12345 and 2nd one xyz then <2> above prints "xyz45".) This
means that clearly m_cRxData (which is a private member) is getting
overwritten. Why does this happen? async_read_from should return immediately
without reading into m_cRxData, readHandler(..) should continue and
complete, and control should reach event loop, and then finally async read
should be done calling the completion handler. Is this explanation wrong?



--
View this message in context: http://boost.2283326.n4.nabble.com/Behaviour-of-asio-tp4642911.html
Sent from the Boost - Users mailing list archive at Nabble.com.
_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users