c++ 实现的简易线程池
2022/5/23 1:05:48
本文主要是介绍c++ 实现的简易线程池,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//单例类 template<typename T> class Singleton { public: static T &instance() { call_once(onceFlag_, [&]{instance_ = new T(); }); return *instance_; } private: Singleton()=default; Singleton(const Singleton&) = delete; Singleton &operator=(const Singleton&) = delete; ~Singleton() = default; static once_flag onceFlag_; static atomic<T *> instance_; }; template<typename T> atomic<T *> Singleton<T>::instance_ = nullptr; template<typename T> once_flag Singleton<T>::onceFlag_; //阻塞队列 template<typename T> class BlockingQueue { public: BlockingQueue() = default; BlockingQueue(const BlockingQueue&) = delete; BlockingQueue& operator=(const BlockingQueue&) = delete; void push(const T& val) { lock_guard<mutex> lock(mutex_); data_.push(val); cond_.notify_one(); } T pop() { unique_lock<mutex> lock(mutex_); while (data_.empty()) { cond_.wait(lock); } T tmp = data_.front(); data_.pop(); return tmp; } private: queue<T> data_; mutex mutex_; condition_variable cond_; }; //线程池 class TharedPool { public: using Functor = function<void()>; TharedPool(): running_(true), taskQueue_(){ // num_of_computing_thread 是启动的线程数量,全局常量 for (int i = 0; i < num_of_computing_thread; ++i) { threads_.push_back(thread(&workerThread,this)); } } void post(Functor functor) { taskQueue_.push(functor); } //强制停止,不保证任务队列执行完毕。因为理论上线程池应该做成单例模式,与进程的生命周期相同,其实不用怎么考虑销毁,这边是特意先讨论下如何销毁才写上的 void stop() { running_ = false; //发送空任务,进行“唤醒” for (int i = 0; i < threads_.size(); ++i) { post([] {}); } for (int i = 0; i < threads_.size(); ++i) { threads_[i].join(); } } private: static void workerThread(TharedPool* tp) { while (tp->running_) { Functor task = tp->taskQueue_.pop(); task(); } } BlockingQueue<Functor> taskQueue_; vector<thread> threads_; bool running_; }; //配合上面的单例模式使用,或者写个单例模式类进行包装
这篇关于c++ 实现的简易线程池的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升