【问题标题】:boost asio - io_service don't wait connection into threadsboost asio - io_service 不要等待连接到线程
【发布时间】:2020-05-27 11:52:07
【问题描述】:

我想创建一个多线程异步服务器。 当我创建一个 thread_group 并以异步方式等待一些连接时。我的程序不会等待并立即终止。

void Server::configServer() {
    _ip = boost::asio::ip::address_v4::from_string("127.0.0.1");
    boost::asio::ip::tcp::resolver resolver(_io_service);
    _endpoint = *resolver.resolve({tcp::v4(), _port});
    std::cout << "Server address: " << _ip.to_string() << ":" << _port << std::endl;

    _acceptor.close();
    _acceptor.open(_endpoint.protocol());
    _acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
    _acceptor.bind(_endpoint);
    _acceptor.listen();
    for (int i = 0; i < 8; ++i) {
        _threads.create_thread(boost::bind(&boost::asio::io_service::run, &_io_service));
    }
    _threads.join_all();
    std::cout << "Server is set up" << std::endl;
    run();
}

void Server::run() {
    Connection::pointer newConnection = Connection::create(_acceptor.get_io_service());
    std::cout << "Server is running" << std::endl;

    _acceptor.async_accept(newConnection->socket(),
        boost::bind(&Server::handleAccept, this, newConnection,
        boost::asio::placeholders::error));
}

void Server::handleAccept(Connection::pointer newConnection, const boost::system::error_code& error) {
    if (!error) {
        std::cout << "Reçu un client!" << std::endl;
        newConnection->start();
        run();
    }
}

你能告诉我我做错了什么吗?

【问题讨论】:

    标签: c++ multithreading tcp network-programming boost-asio


    【解决方案1】:

    run 只要有待处理的待处理任务/处理程序就可以工作。

    在您的情况下,您启动了run,然后调用了第一个async_ 方法。所以run 立即结束,因为没有处理程序被调用。

    您应该初始化一些异步任务,然后调用run 或使用名为work guard 的对象。您没有指定使用哪个版本的 Boost,但有两种选择:

    • 在老年人中io_service/io_context::work (ref)
    • 当前,executor_work_guard (ref)

    在您的班级中,您可以添加 executor_work_guard 作为附加成员变量:

    class Server {
        boost::asio::io_context _io_service;
        boost::asio::executor_work_guard<boost::asio::io_context::executor_type> guard;
    
        Server() : ...., guard(boost::asio::make_work_guard(_io_service)) {
    
        }
    };
    

    使用这种方法,即使没有要处理的处理程序,run 也不会返回。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 2017-09-17
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多