运行 在提升线程中提升 asio io_service
Running boost asio io_service in a boost thread
我正在使用 boost daytime 示例作为一个项目的启动器,该项目需要机器之间的 2 种方式通信,现在需要在其自己的线程中启动 asio io_service 以便我可以单独传递数据。这是我的代码的基础:http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime7/src.html
如果我用
调用 main 中的服务,一切正常
io_service.run()
但是,如果我尝试创建一个线程组并像这样启动:
int main()
{
boost::thread_group tgroup;
try
{
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
tgroup.join_all();
return 0;
}
代码编译并运行,cout 正确引用了端口号,但它似乎没有打开侦听端口,因为客户端连接被拒绝,尽管服务器程序似乎正在等待连接。
请问这里发生了什么?
我猜你的代码可以工作,如果你把 tgroup.join_all();
放在 catch
之前:
...
try {
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;
tgroup.join_all();
}
...
io_service
并且服务器对象超出范围并被销毁,可能在线程组中的线程甚至开始之前 运行.
我正在使用 boost daytime 示例作为一个项目的启动器,该项目需要机器之间的 2 种方式通信,现在需要在其自己的线程中启动 asio io_service 以便我可以单独传递数据。这是我的代码的基础:http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime7/src.html
如果我用
调用 main 中的服务,一切正常io_service.run()
但是,如果我尝试创建一个线程组并像这样启动:
int main()
{
boost::thread_group tgroup;
try
{
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
tgroup.join_all();
return 0;
}
代码编译并运行,cout 正确引用了端口号,但它似乎没有打开侦听端口,因为客户端连接被拒绝,尽管服务器程序似乎正在等待连接。
请问这里发生了什么?
我猜你的代码可以工作,如果你把 tgroup.join_all();
放在 catch
之前:
...
try {
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;
tgroup.join_all();
}
...
io_service
并且服务器对象超出范围并被销毁,可能在线程组中的线程甚至开始之前 运行.