Ricardo Abreu | 12 May 20:22

[asio] async_write and callback order

Hi all,

I tried to clarify this on the irc but no one was sure about it:
   - when calling async_write multiple times, is there any guarantee 
that the handle_write callback I pass is called in the same order?

For instance, I have the following code:

#include "TCPConnection.h"
#include <boost/bind.hpp>
#include <iostream>

using boost::system::error_code;
using boost::bind;
using namespace boost::asio;
using namespace boost::asio::ip;

namespace SockExperiment
{

 
//---------------------------------------------------------------------------------------
     void TCPConnection::handleWrite(const error_code& error, size_t 
bytes_transferred)
     {
         std::string tmp = mBuffer.front(); // Copy the first element 
for printing
         mBuffer.pop(); // erase the first element

         std::cout << "writen msg \"" << tmp << "\".\n"
             << bytes_transferred << " bytes transferred." << std::endl;
     }

 
//---------------------------------------------------------------------------------------
     void TCPConnection::write(const std::string& msg)
     {
         /* Although the buffers object may be copied as necessary, 
ownership of the underlying
         memory blocks is retained by the caller, which must guarantee 
that they remain valid
         until the handler is called. */
         mBuffer.push(msg);
         async_write(mSocket, buffer(mBuffer.back()),
             bind(&TCPConnection::handleWrite, shared_from_this(),
             placeholders::error, placeholders::bytes_transferred));
     }
}

... where mBuffer is an std::queue<std::string>, member of 
TCPConnection. Can I be sure that handleWrite will be called in the same 
order as write and, thus, that I will always pop the right element off 
of mBuffer? Otherwise, what is the proper way of ensuring that the 
memory I pass to asio::buffer remains valid?

Thank you for the attention,
Ricardo

Gmane