我使用 boost asio 像这样处理每个线程的 session :
Server::Server(ba::io_service& ioService, int port): ioService_(ioService), port_(port)
{
ba::ip::tcp::acceptor acceptor(ioService_, ba::ip::tcp::endpoint(ba::ip::tcp::v4(), port_));
for (;;)
{
socket_ptr sock(new ba::ip::tcp::socket(ioService_));
acceptor.accept(*sock);
boost::thread thread(boost::bind(&Server::Session, this, sock));
}
}
void Server::Session(socket_ptr sock)
{
const int max_length = 1024;
try
{
char buffer[256] = "";
// HandleRequest() function performs async operations
if (HandleHandshake(sock, buffer))
HandleRequest(sock, buffer);
ioService_.run();
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
std::cout << "Session thread ended \r\n"; // THIS LINE IS NEVER REACHED
}
在 Server::Session() 中,我有时使用 async_read_some() 和 async_write() 函数执行异步 io。 一切正常,为了让它正常工作,我必须在我的生成线程中调用 ioService_.run() ,否则 Server::Session() 函数退出并且它不处理所需的 io 工作。
问题是从我的线程调用的 ioService_.run() 将导致线程根本不退出,因为与此同时其他请求到达我的监听服务器套接字。
我最终得到的是线程开始并处理现在的 session ,但从不释放资源(结束)。使用这种方法时是否可以只使用一个 boost::asio::io_service ?
最佳答案
我相信您正在寻找 run_one()
或 poll_one()
这将允许您让线程执行就绪处理程序(轮询)或等待处理程序(运行)。通过只处理一个,您可以选择在退出线程之前执行多少个。与执行所有处理程序直到 io_service
停止的 run()
不同。 poll()
在处理完所有当前就绪的数据后将停止。
关于c++ - boost asio - session 线程不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052260/