[英]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,但有兩個選項:
在您的課程中,您可以添加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.