我使用這種方法
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實現使用線程池?](https://stackoverflow.com/questions/15666443/which-stdasync-implementations-use-thread-pools) –