C++11线程池实现
2020-01-15 07:40
706 查看
概述
本文所提线程池以c++11为基础,依赖c++11一些新特性,如thread、funciton等特性。线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程,每个线程使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。其组成部分分为以下四块:
- 线程管理器:用于创建并管理线程池
- 工作线程:线程池中线程
- 任务接口:每个人物必须实现的接口,以供工作线程调度任务的执行
- 任务队列:用于存放没有处理的任务,提供一种缓冲机制
部分代码实现
- 入任务队列,并唤醒空闲线程
std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // don't allow enqueueing after stopping the pool if (stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task]() { (*task)(); }); } condition.notify_one();
- 出任务队列
std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop();
- 析构函数
condition.notify_all(); for (std::thread &worker : workers) worker.join();
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- c++11最简单的线程池实现
- CAFFE2中C++11实现的线程池
- CAFFE2中C++11实现的线程池
- c++11实现线程池
- CAFFE2中C++11实现的线程池
- 使用C++11 实现的线程池
- C++11 STL线程库实现一个简单的线程池
- functional助力C++11实现高度可重用接口-线程池例子
- CAFFE2中C++11实现的线程池
- 使用C++11实现一个半同步半异步线程池
- CAFFE2中C++11实现的线程池
- c++11线程池实现
- C++11:借助C++11特性简单高效实现线程池
- CAFFE2中C++11实现的线程池
- 基于c++11的100行实现简单线程池
- C++11线程池的实现
- c++11 实现半同步半异步线程池
- C++11简化线程池的实现
- 基于C++11实现的线程池
- 托管C++线程锁实现 c++11线程池