异步调用Read立即返回

时间:2016-04-20 14:53:05

标签: c++ asynchronous

我一直在尝试使用boost来异步读取serial_port,直到它将传入的数据放入我指定的缓冲区。但是,当我打电话时:

boost::asio::async_read(*port_, 
                        *readBuf_,
                        boost::bind(&Serial::async_read_handler, 
                                    this, 
                                    boost::asio::placeholders::error, 
                                    boost::asio::placeholders::bytes_transferred));

立即调用async_read_handler,这会触发我read_handler内的代码。

void Serial::async_read_handler(const boost::system::error_code &e, 
                                std::size_t bytes_read)
{
    namespace basio = boost::asio;
    if(!e)
    {
        std::cout << e.message() << std::endl;
        std::cout << bytes_read << std::endl;

        if(bytes_read <= 0)
        {
            std::string read = *basio::buffer_cast<std::string*>(*readBuf_);
            std::cout << read << std::endl;
            basio::async_read(*port_, 
                              *readBuf_, 
                              boost::bind(&Serial::async_read_handler, 
                                          this, 
                                          basio::placeholders::error, 
                                          basio::placeholders::bytes_transferred));
        }
        else
        {
            std::string read = *basio::buffer_cast<std::string*>(*readBuf_);
            std::cout << read << std::endl;
            std::cout << "Bytes read: " << bytes_read << std::endl;
        }
    }
    else
    {
        std::cerr << e.message() << std::endl;
    }
}

我首先调用一个线程在我的主

中运行async_read
int main()
{
    boost::asio::io_service io;
    Serial::Serial serial(PORT, &io);
    if(!serial.is_open())
    {
        serial.open(PORT);
    }
    serial.async_read();
    io.run();
    return 0;
}

我希望async_read调用等到它从缓冲区读取数据以调用处理程序。我怎样才能做到这一点?感谢。

0 个答案:

没有答案