2016-11-25 675 views
0

標準功能std::async是否有使用線程池的std :: async的實現?

模板函數異步異步(可能在一個單獨的線程可以是一個線程池的一部分)運行函數f,並返回一個std ::未來,最終將容納結果該函數調用。

有兩個發射政策std::launch::async and std::launch::deferred。在我的編譯器(GCC 6.2)標準庫推理中,第一個總是創建一個新線程,第二個對調用線程進行懶惰評估。默認使用std::launch::deferred

是否有一些實現使用大小等於可用硬件線程的線程池,當指定std::launch::async時,避免在遞歸算法中使用std::async時創建兩個多線程?

+0

[哪個std :: async實現使用線程池?](https://stackoverflow.com/questions/15666443/which-stdasync-implementations-use-thread-pools) –

回答

1

Microsoft的編譯器和C++運行庫隨Visual Studio一起提供。

0

我使用這種方法

class ThreadPool 
{ 
public: 
    ThreadPool(size_t n) 
     : work_(io_service_) 
    { 
     AddThreads(n); 
    } 
    /** 
    * \brief Adds \a n threads to this thread pool 
    * \param n - count of threads to add 
    */ 
    void AddThreads(size_t n) 
    { 
     for (size_t i = 0; i < n; i++) 
      threads_.create_thread(boost::bind(&boost::asio::io_service::run, &io_service_)); 
    } 
    /** 
    * \brief Count of thread in pool 
    * \return number 
    */ 
    size_t Size() const 
    { 
     return threads_.size(); 
    } 
    ~ThreadPool() 
    { 
     io_service_.stop(); 
     threads_.join_all(); 
    } 

    /** 
    * \brief Perform task \a pt. see io_service::post 
    * \tparam T - type with operator() defined 
    * \param pt - functional object to execute 
    */ 
    template <class T> 
    void post(std::shared_ptr<T> &pt) 
    { 
     io_service_.post(boost::bind(&T::operator(), pt)); 
    } 

    /** 
    * \brief Perform task \a pt. see io_service::dispatch 
    * \tparam T - type with operator() defined 
    * \param pt - functional object to execute 
    */ 
    template <class T> 
    void dispatch(std::shared_ptr<T> &pt) 
    { 
     io_service_.dispatch(boost::bind(&T::operator(), pt)); 
    } 

private: 
    boost::thread_group threads_; 
    boost::asio::io_service io_service_; 
    boost::asio::io_service::work work_; 
}; 

dispatchasynk(..., async); postasynk(..., deferred);