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

Boost Asio: waiting until thread_group has processed all posted tasks?

本文关键字:任务 处理 Asio 等待 thread group Boost      更新时间:2023-10-16

我有一个对象,一旦创建,它就会在后台执行许多任务,但应该阻止直到l/all/posted任务完成。即:

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

所以我被卡住了。。。似乎我可以永远等待,也可以在每个线程中当前运行的作业之后切断队列。文件里一定有我遗漏的东西?

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

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