【问题标题】:boost asio - session thread does not endboost asio - 会话线程没有结束
【发布时间】: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


【解决方案1】:

我相信您正在寻找run_one()poll_one() 这将允许您让线程执行就绪处理程序(轮询)或等待处理程序(运行)。通过只处理一个,您可以在退出线程之前选择要执行的数量。与 run() 相反,它执行所有处理程序,直到 io_service 停止。 poll() 在处理完所有当前准备好的文件后会停止。

【讨论】:

  • 感谢您指出这一点。我使用您提到的功能进行了一些试验,但就我而言,很难知道我需要调用 run_one() 多长时间,因为与此同时,其他连接请求正在到达我的服务器(调度其他线程)并且它们所有这些都由相同的 io_service 处理。简化了我的概念验证程序不使用线程的事情。
【解决方案2】:

我在这里构建处理连接的方式很糟糕。 有一个很好的视频介绍如何设计你的 asio 服务器波纹管(由 asio creator 制作) Thinking Asynchronously: Designing Applications with Boost Asio

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-05
    • 2011-12-18
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    相关资源
    最近更新 更多