
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?
Although async.read returns immediately, it submits your buffer for some *asynchronous* read operation, i.e. the buffer gets filled asynchronously. So, from the point where you issue the async.read until the point of completion handler call you may not make any assumptions regarding the buffer contents.