簡體   English   中英

boost asio - io_service 不等待連接到線程

[英]boost asio - io_service don't wait connection into threads

我想用多線程創建一個服務器異步。 當我創建一個 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();
    }
}

你能告訴我我做錯了什么嗎?

run工作,只要有要處理任何未決的任務/處理程序。

在您的情況下,您開始run ,然后調用了第一個async_方法。 由於沒有要調用的處理程序,因此run立即結束。

您應該初始化一些異步任務,然后調用run或使用名為work guard 的對象。 您沒有指定使用哪個版本的 Boost,但有兩個選項:

  • 在老年人io_service / io_context::work ( ref )
  • 當前, executor_work_guard參考

在您的課程中,您可以添加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也不會返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM