C++ 异步写入完成处理程序最早何时完成?
考虑一个C++ 异步写入完成处理程序最早何时完成?,c++,boost,C++,Boost,考虑一个boost::asioTCP服务器程序中的Connection类,它看起来像这样 #ifndef CONNECTION_HPP #define CONNECTION_HPP #include <iostream> #include <boost/asio.hpp> namespace Transmission { class Connection { public: using SocketType = boost::a
boost::asio
TCP服务器程序中的Connection
类,它看起来像这样
#ifndef CONNECTION_HPP
#define CONNECTION_HPP
#include <iostream>
#include <boost/asio.hpp>
namespace Transmission
{
class Connection
{
public:
using SocketType = boost::asio::ip::tcp::socket;
explicit Connection(boost::asio::io_service& io_service)
: m_socket{io_service},
m_outputBuffer{},
m_writeBuffer{},
m_outputStream{&m_outputBuffer},
m_writeStream{&m_writeBuffer},
m_outputStreamPointer{&m_outputStream},
m_writeStreamPointer{&m_writeStream},
m_outputBufferPointer{&m_outputBuffer},
m_writeBufferPointer{&m_writeBuffer},
m_awaitingWrite{false},
m_pendingWrites{false}
{
}
template<typename T>
void write(const T& output)
{
*m_outputStreamPointer << output;
writeToSocket();
}
template<typename T>
std::ostream& operator<<(const T& output)
{
write(output);
m_pendingWrites = true;
return *m_outputStreamPointer;
}
std::ostream& getOutputStream()
{
writeToSocket();
m_pendingWrites = true;
return *m_outputStreamPointer;
}
void start()
{
write("Connection started");
}
SocketType& socket() { return m_socket; }
private:
void writeToSocket();
SocketType m_socket;
boost::asio::streambuf m_outputBuffer;
boost::asio::streambuf m_writeBuffer;
std::ostream m_outputStream;
std::ostream m_writeStream;
std::ostream* m_outputStreamPointer;
std::ostream* m_writeStreamPointer;
boost::asio::streambuf* m_outputBufferPointer;
boost::asio::streambuf* m_writeBufferPointer;
bool m_awaitingWrite;
bool m_pendingWrites;
};
}
#endif
如果不是很明显,连接使用双缓冲系统来确保没有缓冲区同时被异步写入和变异
我想问的代码是:
std::ostream& getOutputStream()
{
writeToSocket(); // Kicks off an async_write, returns immediately.
m_pendingWrites = true; // Tell async_write complete handler there's more to write
return *m_outputStreamPointer; // Return the output stream for the user to insert to.
}
这样就可以像这样使用连接:myConnection.getOutputStream()您引用的文档位仅表示在返回当前线程之前不会调用处理程序,因此在单线程世界中,您可以得到保证
但是,如果有多个线程运行io任务(io_context::run
和friends,或者隐式使用thread_pool
),仍然存在相同的竞争
您可以在串上发布与连接相关的所有异步任务(串是序列化所有发布任务的执行器,请参见文档中的内容)时反操作此操作
std::ostream& getOutputStream()
{
writeToSocket(); // Kicks off an async_write, returns immediately.
m_pendingWrites = true; // Tell async_write complete handler there's more to write
return *m_outputStreamPointer; // Return the output stream for the user to insert to.
}
std::ostream& getOutputStream()
{
writeToSocket(); // Kicks off an async_write, returns immediately.
// Async_write's completion handler executes.
m_pendingWrites = true; // Tell async_write complete handler there's more to write
// Completion handler already executed so m_pendingWrites = true does nothing.
return *m_outputStreamPointer; // Return the output stream for the user to insert to.
}