線程池實際上也是一個生產者消費者模型,線程池可以讓多個線程去任務隊列中取任務,執行任務,適用于需要大量的線程來完成任務且完成任務的時間較短。
#include "log.hpp"
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include <functional>namespace thread_pool_module
{using namespace log_module;const size_t default_thread_count = 4;//任務類型//約定任務就是線程的回調方法//任務應該是無參無返回值的的調用對象template <class T>class thread_pool{private://只指定線程數量thread_pool(size_t thread_count = default_thread_count):_threads(thread_count),_wait_thread_count(0),_is_running(false){LOG(LOG_LEVEL::INFO) << "thread_pool init";}//拷貝構造函數thread_pool(const thread_pool<T>&) = delete;//賦值構造函數thread_pool<T>& operator=(const thread_pool<T>&) = delete;//線程獲取任務void thread_get_task(){//線程一直不停地獲取任務while(true) {std::unique_lock<std::mutex> lock(_mutex);while(_task_queue.empty() && _is_running){//等待任務++_wait_thread_count;_condition.wait(lock); --_wait_thread_count;}//線程池停止運行并且任務隊列為空if(!_is_running && _task_queue.empty()){return;}//獲取任務T& task = _task_queue.front();_task_queue.pop();//執行任務LOG(LOG_LEVEL::INFO) << "thread_get_task, run task" << std::this_thread::get_id();task();} }public:static thread_pool<T> &get_instance(size_t thread_count = default_thread_count){static thread_pool<T> instance(thread_count);return instance;}//啟動線程池void start(){ if(_is_running){return;}_is_running = true;LOG(LOG_LEVEL::INFO) << "thread_pool start ";for(std::thread& t : _threads){std::function<void()> f = std::bind(&thread_pool<T>::thread_get_task, this);t = std::thread(f);}}//添加任務void add_task(const T& task){if(!_is_running){ LOG(LOG_LEVEL::ERROR) << "thread_pool is not running";return;}_mutex.lock();_task_queue.push(task);if(_wait_thread_count > 0){_condition.notify_one();}_mutex.unlock();}//等待線程池中的任務執行完畢void wait(){for(std::thread& t : _threads){LOG(LOG_LEVEL::INFO) << "thread_pool wait " << t.get_id();t.join();}}//停止線程池void stop(){if(!_is_running){LOG(LOG_LEVEL::ERROR) << "thread_pool is not running";return;}LOG(LOG_LEVEL::INFO) << "thread_pool stop";_is_running = false;_condition.notify_all();}private:std::vector<std::thread> _threads;std::queue<T> _task_queue;std::mutex _mutex;std::condition_variable _condition; //表示線程池中是否有任務size_t _wait_thread_count; //等待任務的線程數量bool _is_running; //線程池是否在運行};}