mercredi 24 juin 2015

boost asio priority queue, add async operation from handler

I have a problem with a design based on the priority queue example from boost asio. If I add a wrapped handler from within a handler it seems to get lost:

See http://ift.tt/1Hf6ZeU for the example.

I have used everything as is and replaced the main() function with the code below:

void low_priority_handler()
{
  std::cout << "Low priority handler\n";
}

int main()
{
  //
  // BASED ON prioritised_handlers.cpp
  // ~~~~~~~~~~~~~~~~~~~~~~~~
  //
  // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  //
  // Distributed under the Boost Software License, Version 1.0. (See accompanying
  // file LICENSE_1_0.txt or copy at http://ift.tt/KQH2Xb)
  //



  //----------------------------------------------------------------------
  using boost::asio::ip::tcp;
  boost::asio::io_service io_service;

  handler_priority_queue pri_queue;

  // Post a completion handler to be run immediately.
  io_service.post(pri_queue.wrap(0, low_priority_handler));


  // Set a deadline timer to expire immediately.
  boost::asio::deadline_timer timer1(io_service);
  timer1.expires_at(boost::posix_time::neg_infin);
  timer1.async_wait(pri_queue.wrap(42, [](const boost::system::error_code& )
                                   {
                                     std::cout << "now" << std::endl;
                                   }));
  // Set a deadline timer to expire later.
  boost::asio::deadline_timer timer2(io_service, boost::posix_time::milliseconds(100));
  boost::asio::deadline_timer timer3(io_service, boost::posix_time::milliseconds(200));
  timer2.async_wait(pri_queue.wrap(100, [&pri_queue, &timer3](const boost::system::error_code& )
                                   {
                                     std::cout << "100ms" << std::endl;
                                     timer3.async_wait(pri_queue.wrap(100, [](const boost::system::error_code& )
                                                                      {
                                                                        std::cout << "200ms" << std::endl;
                                                                      }));

                                   }));

  while (io_service.run_one())
    {
      // The custom invocation hook adds the handlers to the priority queue
      // rather than executing them from within the poll_one() call.
      while (io_service.poll_one())
        ;

      pri_queue.execute_all();
    }
}

This prints:

now
Low priority handler
100ms

And the 200ms printout from timer3 is missing. Based on my printf debugging approach the custom invocation hook asio_handler_invoke() never gets called for the "200ms" action. Unfortunately I cannot see why.

What is wrong with above approach?

Aucun commentaire:

Enregistrer un commentaire