c++ - boost asio 在线程中运行 io_service

标签 c++ multithreading boost boost-asio

我尝试使用 boost::asio 和 boost::thread 运行异步网络线程。 但是 async_accept 立即返回错误代码 125 - 操作已取消......

附上问题的最小示例:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

class Server{

public:
    Server()
    { }

    void listen(unsigned int port)
    {
        boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
        boost::asio::ip::tcp::acceptor acceptor(m_io_service, endpoint);

        std::cout << "Waiting for incomming connection on port: " << port << std::endl;

        acceptor.async_accept(*m_stream.rdbuf(), boost::bind( &Server::handleAccept, this,  boost::asio::placeholders::error, boost::ref( acceptor ) ) );
        m_listenThread = new boost::thread(boost::bind(&boost::asio::io_service::run, &m_io_service));

    }

    void stop()
    {
        m_listenThread->join();
    }

private:

    void handleAccept(const boost::system::error_code& error, boost::asio::ip::tcp::acceptor& acceptor)
    {
        std::cout << "receiverd incomming connection" << std::endl;
        if(error)
            std::cout << "ERROR: " << error.message() << "(" << error.value() << ")" << std::endl;

    }

    boost::asio::io_service m_io_service;
    boost::asio::ip::tcp::iostream m_stream;
    boost::thread* m_listenThread;


};



int main(int argc, char *argv[])
{
    Server server;
    server.listen(10000);

    while(1);
}

最佳答案

acceptor::async_accept 立即返回,在出现错误或连接被接受时安排调用处理程序 (1)

listen() 函数正在返回,这导致了接受器 (2) 的破坏

当一个acceptor(或socket,或deadline_timer)被销毁时,所有挂起的处理程序都被调度到io_service 错误代码为 asio::error::operation_aborted。这是为了满足 async_ 函数的后置条件(即,“处理程序将恰好被调用一次,就像 io_service.post() 一样”)(3)

因此,在第 (2) 点,正在安排您的处理程序 - 就在代码返回主循环之前。

修复:

确保 acceptor 在处理程序被调用之前存在。这是 asio 异步编程中的标准做法。 boost 网站上的示例将帮助您理解(稀疏的)asio 文档。

不要失去希望。我花了很长时间才学会如何正确使用 asio,并意识到它有多么强大。

关于c++ - boost asio 在线程中运行 io_service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746483/

相关文章:

c++ - 如何使用 libviso2?

c++ - 简单的欧拉物理,奇怪的行为

c++ - 模板特化子类

c++ - 如何将参数传递给已经开始运行的线程

c++ - 寻找 boost::iterator_facade 的示例用法

c++ - c++中数组的动态内存分配

java - Java 中不同步的 getter/setter 行为

java - 多线程中类加载器的行为

boost::spirit::karma 输出引号内的字符串

c++ - 通过 cmd 同时运行 2 个或更多属于不同测试套件的 boost 测试用例