Boost Asio:等到thread_group处理完所有发布的任务?

时间:2012-01-31 13:47:05

标签: c++ boost boost-asio

我有一个对象,一旦创建在后台执行许多任务,但应该阻止直到/所有/已发布的任务完成。即:

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);
    }
};

所以我被困了......似乎我可以永远等待或者在每个线程中当前正在运行的作业之后切断队列。文档中一定有我遗漏的内容吗?

1 个答案:

答案 0 :(得分:0)

根据文档,这个想法应该有效(伪代码):

...

// 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();