ASIO 正确处理多线程 + strand + socket + timer
ASIO proper handling of multiple threads + strand + socket + timer
我使用的是最新的 ASIO 版本(目前为 1.18.0)。目前正在设计一个带有定时器(用于超时)的多线程异步 TCP 服务器。我有一个 io_context
有多个线程调用它的 run()
函数。我接受这样的新连接:
void Server::AcceptConnection()
{
acceptor_.async_accept(asio::make_strand(io_context_),
[this](const asio::error_code& error, asio::ip::tcp::socket peer) {
if (!error) {
std::make_shared<Session>(std::move(peer))->run();
}
AcceptConnection();
});
}
这里是 Session
class:
的精简版
class Session : public std::enable_shared_from_this<Session>
{
public:
Session(asio::ip::tcp::socket&& peer) : peer_(std::move(peer)) {}
void run()
{
/*
asio::async_read(peer_, some_buffers_, some_callback_);
timeout_timer_.expires_after();
timeout_timer_.async_wait();
// etc
*/
}
private:
asio::ip::tcp::socket peer_;
asio::steady_timer timeout_timer_{peer_.get_executor()};
}
请注意定时器的初始化。
另外,请注意,我没有为套接字和计时器的异步处理程序使用任何类型的 strand::wrap()
或 asio::bind_executor()
包装器,据我所知,如果我初始化我的,则不再需要它们具有适当执行程序的对象。
这里的问题是:在 TCP 连接正在使用的同一链中使用定时器处理链内 TCP 连接的正确方法是?
注意:定时器用于在超过超时时间后中止 TCP 连接。
是的,这也是我使用新接口编写内容的方式。
我记得当我开始使用新界面时有同样的担忧,并最终检查各种完成处理程序在预期的链上执行运行,他们这样做。
总而言之,这些都大大简化了库的使用。
我使用的是最新的 ASIO 版本(目前为 1.18.0)。目前正在设计一个带有定时器(用于超时)的多线程异步 TCP 服务器。我有一个 io_context
有多个线程调用它的 run()
函数。我接受这样的新连接:
void Server::AcceptConnection()
{
acceptor_.async_accept(asio::make_strand(io_context_),
[this](const asio::error_code& error, asio::ip::tcp::socket peer) {
if (!error) {
std::make_shared<Session>(std::move(peer))->run();
}
AcceptConnection();
});
}
这里是 Session
class:
class Session : public std::enable_shared_from_this<Session>
{
public:
Session(asio::ip::tcp::socket&& peer) : peer_(std::move(peer)) {}
void run()
{
/*
asio::async_read(peer_, some_buffers_, some_callback_);
timeout_timer_.expires_after();
timeout_timer_.async_wait();
// etc
*/
}
private:
asio::ip::tcp::socket peer_;
asio::steady_timer timeout_timer_{peer_.get_executor()};
}
请注意定时器的初始化。
另外,请注意,我没有为套接字和计时器的异步处理程序使用任何类型的 strand::wrap()
或 asio::bind_executor()
包装器,据我所知,如果我初始化我的,则不再需要它们具有适当执行程序的对象。
这里的问题是:在 TCP 连接正在使用的同一链中使用定时器处理链内 TCP 连接的正确方法是?
注意:定时器用于在超过超时时间后中止 TCP 连接。
是的,这也是我使用新接口编写内容的方式。
我记得当我开始使用新界面时有同样的担忧,并最终检查各种完成处理程序在预期的链上执行运行,他们这样做。
总而言之,这些都大大简化了库的使用。