1

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?

Galik
  • 42,526
  • 3
  • 76
  • 100
bobeff
  • 2,800
  • 1
  • 26
  • 51
  • Possible duplicate of [Which std::async implementations use thread pools?](https://stackoverflow.com/questions/15666443/which-stdasync-implementations-use-thread-pools) – Davis Herring Jan 09 '18 at 05:35

2 Answers2

1

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

ahcox
  • 7,846
  • 5
  • 29
  • 36
1

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

user5821508
  • 315
  • 2
  • 10