[英]Is there an implementation of std::async which uses thread pool?
標准函數std :: async :
模板函數async異步運行函數f(可能在單獨的線程中,該線程可能是線程池的一部分),並返回std :: future,該變量最終將保存該函數調用的結果。
有兩個啟動策略std :: launch :: async和std :: launch :: deferred 。 在我的編譯器( GCC 6.2 )標准庫實現中,第一個總是創建一個新線程,第二個總是在調用線程上進行延遲評估。 默認情況下,使用std::launch::deferred
。
是否有一些實現使用線程池,該線程池的大小等於在指定std::launch::async
時可用的硬件線程,以避免在遞歸算法中使用std::async
時創建多個線程?
Visual Studio附帶的Microsoft編譯器和C ++運行時可以。
我正在使用這種方法
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_;
};
dispatch
是asynk(..., async)
; post
是asynk(..., deferred)
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.