title: Is it safe to write to a streambuf while an async_write is pending?
body: <p>Consider the following code:</p>
  
  <pre><code>void TCP::sendMessage(const std::string&amp; msg) {
    std::ostream os{&amp;m_send_streambuf};
    os &lt;&lt; msg;
  
    if (not m_pending_send) {
      doSend();
    }
  }
  
  void TCP::doSend() {
    m_pending_send = true;
    boost::asio::async_write( m_socket, m_send_streambuf
                            , [this](boost::system::error_code ec, std::size_t len)
                              {
                                if (ec) {
                                    throw std::runtime_error(ec.message());
                                }
  
                                m_send_streambuf.consume(len);
  
                                if (m_send_streambuf.size() &gt;= 1) {
                                  // There's still some data to send
                                  doSend();
                                }
                                else {
                                  m_pending_send = false;
                                }
                            });
  }
  </code></pre>
  
  <p><code>m_send_streambuf</code> is a <code>boost::asio::streambuf</code> and <code>m_pending_send</code> indicates wether an asynchronous write is pending.</p>
  
  <p>I'm not sure if it's a good idea to use the <code>streambuf</code> like this as a call to <code>sendMessage</code> will modify the buffer, while an asynchronous write is possibly running.</p>
  
  <p>So, is it safe to use the <code>streambuf</code> like this? Or maybe I should use some kind of double buffering?</p>