C++实现简单的线程池
2022/7/30 14:22:53
本文主要是介绍C++实现简单的线程池,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
// thread_pool.h #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_; };
// thread_pool.cpp #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_); // always use a while-loop, due to spurious wakeup 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; }
这篇关于C++实现简单的线程池的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享