简体   繁体   中英

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

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?

Visual Studio附带的Microsoft编译器和C ++运行时可以。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM