A thread pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program.By maintaining a pool of threads, the model increases performance and avoids latency in execution due to frequent creation and destruction of threads for short-lived tasks.
classThreadPool { public: ThreadPool(size_t); template<class F, class... Args> autoenqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool(); private: // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue std::queue< std::function<void()> > tasks; // 统一为无参数无返回值的函数 // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; };
// the constructor just launches some amount of workers inlineThreadPool::ThreadPool(size_t threads) : stop(false) { for(size_t i = 0;i<threads;++i) workers.emplace_back( [this] { for(;;) { std::function<void()> task;
// add new work item to the pool template<class F, class... Args> autoThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type;