Search code examples
asynchronousboostboost-asio

What is the reason asio doesn't do any delay?


I am new to asio.

Here is guide I was following writing my daytime tcp-server: https://think-async.com/Asio/asio-1.18.1/doc/asio/tutorial/tutdaytime3.html . I was trying to reproduce a reasonable example that would show that asunchronous code is actually asynchronous. I didn't modify anything else, just small piece of code in tcp_server class. I am adding this delay in order to see that after we are waiting timer to expire, we can gracefully handle other client connections/requests. So, did I miss something? Because in my case delay basically doesn't work ;(

void handle_accept(const tcp_connection::pointer &new_connection,
                   const asio::error_code &error) {

    asio::steady_timer timer(io_context_,  asio::chrono::seconds(5));

    std::cout << "Before timer" << std::endl;

    timer.async_wait(std::bind(&tcp_server::handle_wait, this, error, new_connection));
}

void handle_wait(asio::error_code &ec, const tcp_connection::pointer &new_connection) {
    if (!ec) {
        new_connection->start();
    }

    std::cout << "Inside timer" << std::endl;

    start_accept();
}

Solution

  • void handle_accept(const tcp_connection::pointer &new_connection,
                           const asio::error_code &error) {
    
            asio::steady_timer timer(io_context_,  asio::chrono::seconds(5));
    
            std::cout << "Before timer" << std::endl;
    
            timer.async_wait(std::bind(&tcp_server::handle_wait, this, error, new_connection));
        }
    

    The timer is a local variable.

    async_wait returns immediately, without blocking.

    The function exits, destructing the timer. The timer cancels all pending operations (with error::operation_aborted).

    🖛 Make sure the lifetime of the timer extends well enough to allow for it expire (or at least until it stops being relevant). In your case there will probably already be a tcp::acceptor member in your class, and the timer could reside next to it.