首页 文章

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

提问于
浏览
0

标准函数std::async

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

有两个发布政策std::launch::async and std::launch::deferred . 在我的编译器( GCC 6.2 )标准库中,第一个总是创建一个新线程,第二个在调用线程上进行延迟评估 . 默认情况下使用 std::launch::deferred .

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

2 回答

  • 1

    它随Visual Studio一起提供的Microsoft编译器和C运行时 .

  • 0

    我正在使用这种方法

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

相关问题