提升 asio async_read_some 超时

boost asio async_read_some timeout

我使用此代码使用 async_read_some 超时

        readdata=0;
        port_->async_read_some(boost::asio::buffer(vector),
                boost::bind(readCallback));


        //init async timer
        boost::asio::deadline_timer timer(io);
        timer.async_wait(boost::bind(timeoutHandler));
        timer.expires_from_now(boost::posix_time::seconds(5));

        io.reset();
        do {
            io.run_one();
        }
        while (readdata==0);

这是我的回传

void readCallback()
{
    std::cout << "READ CALLBACK: "<<x<<std::endl;
    readdata=1;
    return;
}
void timeoutHandler()
{
   std::cout << "TIMEOUT CALLBACK: "<<x<<std::endl;
   readdata=1;
}

我的问题是 timeoutHandler 是立即执行的,而不是在 5 秒后执行

简单的错误。在调用 async_wait.

之前你应该做 expires_from_now
#include <iostream>
#include <asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
  asio::io_service io_s;
  asio::deadline_timer timer(io_s);
  timer.expires_from_now(boost::posix_time::seconds(5));
  timer.async_wait([](auto err_c) { std::cout << "After 5 seconds" << std::endl; } );

  io_s.reset();

  io_s.run();

  return 0;
}