Is there an implementation of std::async which use

2020-07-30 02:50发布

问题:

The standard function std::async:

The template function async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool) and returns a std::future that will eventually hold the result of that function call.

There is two launch polices std::launch::async and std::launch::deferred. In my compiler's (GCC 6.2) standard library impelmentation, the first one always creates a new thread and the second one does lazy evaluation on the calling thread. By default std::launch::deferred is used.

Is there some implementation which uses thread pool with size equal to the hardware threads available when std::launch::async is specified to avoid creating two many threads when std::async is used in recursive algorithm?

回答1:

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



回答2:

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);