我最近一直在使用boost asio和一些新的C++ 11结构。以下是导致意外行为的代码示例部分(至少对我而言)。asio .async_ *将不会运行,除非主线程调用io_service.run
void Server::startAccept()
{
connections_.push_back(std::make_shared<Connection>(io_service_));
acceptor_.async_accept(connections_.back()->socket(), std::bind(&Server::accept_handler, this, connections_.back(), std::placeholders::_1));
}
void Server::accept_handler(std::shared_ptr<Connection> con, const boost::system::error_code& ec)
{
startAccept();
if (!ec) {
con->start();
}
}
我拨打电话到服务器:: startAccept之前,我创建io_service对象::工作的一个实例,)的std ::线程池,要求io_service_.run(。在我调用startAccept之后,主线程只是等待命令行输入。
我希望我的线程池中的一个线程在连接启动时运行Server :: accept_handler。这不会发生。相反,我必须从主线程调用io_service_.run()。
现在我玩了一段时间,我发现我可以通过这样达到预期的行为:
void Server::startAccept()
{
connections_.push_back(std::make_shared<Connection>(io_service_));
io_service_.post([this]() { acceptor_.async_accept(connections_.back()->socket(), std::bind(&Server::accept_handler, this, connections_.back(), std::placeholders::_1)); });
}
void Server::accept_handler(std::shared_ptr<Connection> con, const boost::system::error_code& ec)
{
startAccept();
if (!ec) {
con->start();
}
}
是什么.async_之间的差异*操作和io_service.post?
编辑:定义BOOST_ASIO_ENABLE_HANDLER_TRACKING
当我编译并运行了一个程序,然后连接到服务器的代码,我包括第一块是这样的输出:
@asio|1350656555.431359|0*1|[email protected]_accept
当我运行第二块代码我包括并连接到服务器我得到这个输出:
@asio|1350656734.789896|0*1|[email protected]EC78.post
@asio|1350656734.789896|>1|
@asio|1350656734.789896|1*2|[email protected]_accept
@asio|1350656734.789896|<1|
@asio|1350656756.150051|>2|ec=system:0
@asio|1350656756.150051|2*3|[email protected]
@asio|1350656756.150051|>3|
@asio|1350656756.150051|2*4|[email protected]_send
@asio|1350656756.150051|3*5|[email protected]_accept
@asio|1350656756.150051|2*6|[email protected]_receive
@asio|1350656756.150051|<3|
@asio|1350656756.150051|>4|ec=system:0,bytes_transferred=54
@asio|1350656756.150051|<2|
@asio|1350656756.150051|<4|
@asio|1350656758.790803|>6|ec=system:10054,bytes_transferred=0
@asio|1350656758.790803|<6|
编辑2:创建线程的洞察力
for (int i = 0; i < NUM_WORKERS; i++) {
thread_pool.push_back(std::shared_ptr<std::thread>(new std::thread([this]() { io_service_.run(); })));
}
注意,它并没有成为_main_线程,它可以是任何线程。实际上它可能是_多个线程。 –
@ K-ballo我已经从另一个不是主线程的线程调用了io_service.run。只有在我提供的第一个代码块中的主线程调用io_service.run时,才会执行Server :: accept_handler。 – flumpb
最初的代码和描述看起来很好,并且这种行为通常会来自[work](http://www.boost.org/doc/libs/1_51_0/doc/html/booster_asio/reference/io_service__work.html)对象超出范围。但是,它没有解释后一种行为。也许启用[BOOST_ASIO_ENABLE_HANDLER_TRACKING](http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/overview/core/handler_tracking.html)将提供一些见解。 –