Existe-t-il une implémentation de std::async qui utilise thread pool?
la fonction standard std:: async :
la fonction template async exécute la fonction de manière asynchrone (potentiellement dans un thread séparé qui peut faire partie d'un pool de threads) et renvoie un std::future qui éventuellement tiendra le résultat de cet appel de fonction.
il y a deux politiques de lancement std::lancement::async et std::lancement::différé . Dans mon compilateur ( GCC 6.2 ) impelmentation bibliothèque standard, le premier crée toujours un nouveau fil et le second fait une évaluation paresseuse sur le fil appelant. Par défaut std::launch::deferred
est utilisé.
y a-t-il une implémentation qui utilise un pool de threads de taille égale aux threads matériels disponibles lorsque std::launch::async
est spécifié pour éviter de créer deux nombreux threads lorsque std::async
est utilisé dans un algorithme récursif?
2 réponses
compilateur de Microsoft et C++ runtime qu'il fournit avec Visual Studio.
j'utilise cette approche
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
est asynk(..., async)
;
post
est asynk(..., deferred)
;