是否有使用线程池的 std::async 的实现?

Is there an implementation of std::async which uses thread pool?

本文关键字:std 实现 async 线程 是否      更新时间:2023-10-16

标准函数std::async:

模板函数异步运行函数 f(可能在可能是线程池一部分的单独线程中)并返回一个 std::future,该函数最终将保存该函数调用的结果。

有两种启动策略 std::launch::async 和 std::launch::d eferred。在我的编译器(GCC 6.2)标准库影响中,第一个总是创建一个新线程,第二个对调用线程进行惰性计算。默认情况下,使用std::launch::deferred

是否有一些实现使用线程池的大小等于指定std::launch::async时可用的硬件线程,以避免在递归算法中使用std::async时创建两个多个线程?

Microsoft的编译器和Visual Studio附带的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_;
};

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