是否有使用线程池的 std::async 的实现?
Is there an implementation of std::async which uses thread pool?
标准函数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_;
};
dispatch
asynk(..., async)
;post
是asynk(..., deferred)
;
相关文章:
- 我应该实现右值推送功能吗?我应该使用std::move吗
- std::random_device是如何实现的
- 理解GCC中的std::pow实现
- 在没有未定义行为的情况下实现类似std::vector的容器
- std::unordered_map 搜索算法是如何实现的?
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- std::背后的基本原理assignable_from可能的实现
- 在std::launder之前,std::vector的所有实现都是不可移植的吗?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- C++矩阵类运算符使用 std::common_type_t 和复数的实现
- std::max() 函数与定点实现的比较中的问题
- 使用 std::forward_list 返回错误的队列实现
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- 在 x86 上实现 std::atomic_thread_fence(std::memory_order_seq_cst
- std::extent 实现详细信息说明
- 使用 std::call_once 实现类似单例的功能
- 了解 std::is_base_of 的重新实现
- 如何在跳过所有内部实现的同时跳转到 GDB 中 std::function 中的函数?
- std::实现移动