【发布时间】:2012-02-21 13:28:54
【问题描述】:
我使用 boost asio 来处理每个线程的会话,如下所示:
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。 一切正常,为了让它工作,我必须在我的 spawn 线程中调用 ioService_.run() 否则 Server::Session() 函数退出并且它不处理所需的 io 工作。
问题是从我的线程调用的 ioService_.run() 将导致线程根本不退出,因为与此同时其他请求会到达我的侦听服务器套接字。
我最终得到的是线程启动和处理现在的会话,但从不释放资源(结束)。使用这种方法时是否可以只使用一个 boost::asio::io_service ?
【问题讨论】:
-
这是一种非常奇怪的使用 boost::asio 的方式。你读过教程吗?查看 HTTP Server 3 示例。它使用一个线程池来服务多个连接,每个线程调用
io_service::run()。 -
@mark 我实际上是在寻找一个简单的解决方案,只是我的程序的概念证明。我最终设法做到了,根本没有使用线程
标签: c++ networking boost boost-asio