复制 | |
| #pragma once |
| #include <vector> |
| #include <deque> |
| #include <thread> |
| #include <functional> |
| #include <condition_variable> |
| |
| class ThreadPool { |
| using Task = std::function<void()>; |
| using TaskList = std::deque<Task>; |
| using WorkThreadQueue = std::vector<std::thread*>; |
| |
| public: |
| ThreadPool(); |
| ~ThreadPool(); |
| |
| public: |
| bool Start(uint16_t ThreadNum = 1); |
| void Stop(); |
| void AddTask(const Task&); |
| |
| private: |
| void ThreadLoop(); |
| Task AcceptTask(); |
| |
| private: |
| uint16_t thread_num_; |
| bool is_started_; |
| WorkThreadQueue work_thread_list_; |
| TaskList task_list_; |
| std::mutex thread_pool_mutex_; |
| std::condition_variable condition_variable_; |
| }; |
| |
| #include "thread_pool.h" |
| |
| ThreadPool::ThreadPool() : thread_num_(1), is_started_(false) {} |
| |
| ThreadPool::~ThreadPool() { |
| if (true == is_started_) { |
| Stop(); |
| } |
| } |
| |
| bool ThreadPool::Start(uint16_t ThreadNum) { |
| thread_num_ = ThreadNum; |
| if (false == work_thread_list_.empty()) { |
| return false; |
| } |
| is_started_ = true; |
| |
| work_thread_list_.reserve(thread_num_); |
| for (uint16_t i = 0; i < thread_num_; ++i) { |
| work_thread_list_.push_back(new std::thread(std::bind(&ThreadPool::ThreadLoop, this))); |
| } |
| return true; |
| } |
| |
| void ThreadPool::Stop() { |
| std::lock_guard<std::mutex> Lock(thread_pool_mutex_); |
| is_started_ = false; |
| condition_variable_.notify_all(); |
| for (WorkThreadQueue::iterator it = work_thread_list_.begin(); it != work_thread_list_.end(); ++it) { |
| (*it)->join(); |
| delete *it; |
| } |
| work_thread_list_.clear(); |
| } |
| |
| void ThreadPool::ThreadLoop() { |
| while (true == is_started_) { |
| Task NewTask = AcceptTask(); |
| if (NewTask) { |
| NewTask(); |
| } |
| } |
| } |
| |
| void ThreadPool::AddTask(const Task& NewTask) { |
| std::lock_guard<std::mutex> Lock(thread_pool_mutex_); |
| task_list_.push_back(NewTask); |
| condition_variable_.notify_one(); |
| } |
| |
| ThreadPool::Task ThreadPool::AcceptTask() { |
| std::unique_lock<std::mutex> Lock(thread_pool_mutex_); |
| |
| while (task_list_.empty() && is_started_) { |
| condition_variable_.wait(Lock); |
| } |
| Task NewTask; |
| TaskList::size_type size = task_list_.size(); |
| if (!task_list_.empty() && is_started_) { |
| NewTask = task_list_.front(); |
| task_list_.pop_front(); |
| } |
| return NewTask; |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具