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

£可爱£侵袭症+ 提交于 2019-12-04 21:25:13

Microsoft's compiler and C++ runtime that it ships with Visual Studio does.

i am using this approach

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 is asynk(..., async); post is asynk(..., deferred);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!