[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

Hi Ricardo, IIUC, it's bad idea to call async_write before the previous call to async_write is completed (the same is true for async_read), since it's not guaranteed the "parallel" async_write's/read's are dispatched in the order you wish. The correct flow would be to call next async_write in the writeHandler. You can find lots of examples in ASIO tutorial.
To: boost-users@lists.boost.org> From: gumbeto@gmail.com> Date: Mon, 12 May 2008 19:26:39 +0100> Subject: [Boost-users] [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?> <...> Ricardo>
Explore the seven wonders of the world http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE
participants (2)
-
Igor R.
-
Ricardo Abreu