EddieBytes
EddieBytes

Reputation: 1343

What is the definition of a boost::asio::io_service ready handler?

I am trying to understand the difference between io_service's poll()/poll_one() and run()/run_one(). The difference as stated in the documentation is that poll() executes ready handlers as opposed to run() which executes any handler.

But nowhere in the boost documentation could I find the definition of a 'ready handler'.

A valid answer to this question is one able to show, preferably with a code example, the difference between a ready and non-ready handler and the difference between how poll() and run() executes it.

Thanks.

Upvotes: 5

Views: 1164

Answers (2)

Jesse Good
Jesse Good

Reputation: 52365

int main()
{
    boost::asio::io_service io_service;
    boost::asio::deadline_timer timer(io_service);

    timer.expires_from_now(boost::posix_time::seconds(5));
    timer.async_wait([](const boost::system::error_code& err)
                     { std::cout << (err ? "error" : "okay")
                     ;});

    //io_service.poll_one(); 
    io_service.run_one();
}

If you use io_service.poll_one(); you will most likely not see any output because the timer has not elapsed yet. ready handler simply means a handle that is ready to run (such as when a timer elapses or an operation finishes, etc.). However, if you use io_service.run_one(); this call will block until the timer finishes and execute the handler.

Upvotes: 6

Arne Mertz
Arne Mertz

Reputation: 24606

A "ready handler" is a handler that is ready to be executed. If you have issued an asynchronous call, it gets executed in the background and its handler becomes ready when the async call is done. Before that, the handler is pending, but not ready.

  • poll_one executes one ready handler if there is any.
  • poll executes all ready handlers, but not the pending. Both poll versions return immediately after the execution of the handlers.
  • run_one executes a ready handler if there is one, if not it waits for the first pending handler to become ready, meaning it blocks.
  • run executes and waits, until there are neither ready nor pending handlers. After it returns, the io_servie is in stopped state.

See also Boost::Asio : io_service.run() vs poll() or how do I integrate boost::asio in mainloop

Upvotes: 11

Related Questions