是否有使用线程池的std :: async实现? [英] Is there an implementation of std::async which uses thread pool?
问题描述
标准函数 std :: async :
模板函数async异步运行函数f(可能在单独的线程中,该线程可能是线程池的一部分),并返回std :: future,最终将保留该函数调用的结果.
The template function async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool) and returns a std::future that will eventually hold the result of that function call.
有两个启动策略 std :: launch :: async和std :: launch :: deferred .在我的编译器( GCC 6.2 )标准库的实现中,第一个总是创建一个新线程,第二个总是在调用线程上进行惰性求值.默认情况下,使用std::launch::deferred
.
There is two launch polices std::launch::async and std::launch::deferred. In my compiler's (GCC 6.2) standard library impelmentation, the first one always creates a new thread and the second one does lazy evaluation on the calling thread. By default std::launch::deferred
is used.
是否有一些实现使用线程池,该线程池的大小等于指定std::launch::async
时可用的硬件线程,以避免在递归算法中使用std::async
时创建多个线程?
Is there some implementation which uses thread pool with size equal to the hardware threads available when std::launch::async
is specified to avoid creating two many threads when std::async
is used in recursive algorithm?
推荐答案
我正在使用这种方法
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)
;
这篇关于是否有使用线程池的std :: async实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!