boost:asio thread pool implementation for occasionally synchronized tasks

前端 未结 3 1774
执念已碎
执念已碎 2021-02-04 11:21

I have a \"main\" function that performs many small, independent tasks each once per time step. However, after each time step, I must wait for all of the tasks to complete befor

3条回答
  •  忘了有多久
    2021-02-04 11:41

    Rost's method essentially works, but the boost::make_shared can not compile as is. The following is a working version (in vs2012):

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::vector> pending_data;
    typedef boost::packaged_task task_t;
    
    boost::shared_ptr< boost::packaged_task > pt(new boost::packaged_task ([&,i](){...}));
    boost::unique_future result = pt->get_future();
    pending_data.push_back(boost::move(result));
    io_service.post(boost::bind(&task_t::operator(), pt));
    
    boost::wait_for_all(pending_data.begin(), pending_data.end()); 
    pending_data.clear();
    

    It will not compile if use argument in the packaged_task typedef. This thread pool by asio and future method only saved 8% time compared with each loop create new thread methods.

提交回复
热议问题