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

标准函数std :: async:

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

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

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


它随Visual Studio一起提供的Microsoft编译器和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) ;

链接地址: http://www.djcxy.com/p/30751.html

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

下一篇: C++11 Segmentation fault with std::promise