4

I have an object that once created executes many tasks in the background, but should block untill /all/ posted tasks are finished. I.e.:

struct run_many{
    boost::asio::io_service       m_io_service;
    boost::thread_group           m_threads;
    boost::asio::signal_set       m_signals;

    void evaluate(std::string work, int i){ /*...*/ }

    void run_tasks(int tasks, std::string work){
        {
          boost::asio::io_service::work w(m_io_service); //
          for(int i=0;i<tasks;i++)
               m_io_service.post(boost::bind(&run_many::evaluate, this, work, i));
        }

        //m_io_service.run();  // blocks forever
        m_io_service.stop();   // seems to cut off queued jobs
        m_threads.join_all();  // works only after m_io_service.stop()
    }

    run_many(int n_workers)
    {
        m_threads.create_thread(boost::bind(&boost::asio::io_service::run,m_io_service);
    }
};

So I am stuck... it seems that I can either wait forever or cut off the queue after the currently running job in each thread. There must be something I'm missing in the docs?

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
hannes
  • 966
  • 9
  • 13
  • 1
    `io_service::run()` will return when all work is finished, which is your desired behaviour. The questions is why does your call to `run()` block forever? – nabulke Jan 31 '12 at 14:01
  • OK. I also registered signal_set with the io_service. when I remove the signal set it works as advertised using `m_io_service.run()`. – hannes Jan 31 '12 at 14:26
  • 1
    http://stackoverflow.com/a/7957296/369872 – David Jan 31 '12 at 14:51
  • or http://stackoverflow.com/questions/4705411/boostasio-io-service-run-vs-poll-or-how-do-i-integrate-boostasio-in-ma – Caribou Nov 02 '12 at 00:19

1 Answers1

0

According to the documentation this idea should work(pseudocode):

...

// put a few handlers into io_service

...

// don't forget to destroy all boost::asio::io_service::work objects
while (m_io_service.stopped())
{
m_io_service.run();
}

// when code reaches this line m_io_service will be in stopped state and all handlers will be executed

// this code can be called without any doubts about being locked

m_threads.join_all();
Coreman
  • 71
  • 1
  • 2