c++11 线程池学习笔记 (二) 线程池
学习内容来自以下地址
http://www.cnblogs.com/qicosmos/p/4772486.html
github https://github.com/qicosmos/cosmos
有了任务队列 在程序运行之初 就预开启多个执行任务的线程 等待任务队列中传来的元素 对元素进行处理 执行完毕后 也不销毁线程 而是等待下个元素进行处理
使用std::list<std::shared_ptr<std::thread>> m_threadgroup; 变量记录线程指针 方便管理
测试例子中传递的元素类型定义为 td::function<void()> 即一个返回类型为void 无输入参数的函数
对应代码为using Task = std::function<void()>;
每当队列中添加该元素TASK 则有线程从队列中取出执行
代码如下
#pragma once #include <list>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream> using namespace std; template<typename T>
class SyncQueue {
public:
SyncQueue(int maxSize):m_maxSize(maxSize),m_needStop(false){}
void Put(const T& x) {
Add(x);
}
void Put(T&& x) {
Add(std::forward<T>(x));
}
void Take(std::list<T>& list) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] {return m_needStop || NotEmpty(); });
if (m_needStop)
return;
list = std::move(m_queue);
m_notFull.notify_one();
} void Take(T& t) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] {return m_needStop || NotEmpty(); });
if (m_needStop)
return;
t = m_queue.front();
m_queue.pop_front();
m_notFull.notify_one();
} void Stop() {
{
std::lock_guard<std::mutex> locker(m_mutex);
m_needStop = true;
}
m_notFull.notify_all();
m_notEmpty.notify_all();
} bool Empty() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.empty();
} bool Full() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size() == m_maxSize;
} size_t Size() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size();
} int Count() {
return m_queue.size();
}
private:
bool NotFull()const {
bool full = m_queue.size() >= m_maxSize;
if (full)
cout << "buffer area is full,wait..." << endl;
return !full;
}
bool NotEmpty()const {
bool empty = m_queue.empty();
if (empty)
cout << "buffer area is empty,wait... " <<
" threadID: " << this_thread::get_id() <<endl;
return !empty;
} template<typename F>
void Add(F&& x) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notFull.wait(locker, [this] {return m_needStop || NotFull(); });
if (m_needStop)
return;
m_queue.push_back(std::forward<F>(x));
m_notEmpty.notify_one();
}
private:
std::list<T> m_queue;
std::mutex m_mutex;
std::condition_variable m_notEmpty;
std::condition_variable m_notFull;
int m_maxSize;
bool m_needStop;
};
SyncQueue.h
// ThreadPool.cpp: 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <list>
#include <thread>
#include <functional>
#include <memory>
#include <atomic>
#include "SyncQueue.h" const int MaxTaskCount = ;
class ThreadPool {
using Task = std::function<void()>;
public:
ThreadPool(int numThreads = std::thread::hardware_concurrency()) :m_queue(MaxTaskCount) {
Start(numThreads);
}
~ThreadPool(void) {
Stop();
}
void Stop() {
std::call_once(m_flag, [this] {StopThreadGroup(); });
}
void AddTask(Task&& task) {
m_queue.Put(std::forward<Task>(task));
}
void AddTask(const Task& task) {
m_queue.Put(task);
} void Start(int numThreads) {
m_running = true;
for (int i = ; i < numThreads; i++) {
m_threadgroup.push_back(std::make_shared<std::thread>(&ThreadPool::RunInThread, this));
}
}
private:
void RunInThread() {
while(m_running) {
std::list<Task> list;
m_queue.Take(list); for (auto& task : list) {
if (!m_running)
return;
task();
}
}
} void StopThreadGroup() {
m_queue.Stop();
m_running = false;
for (auto thread : m_threadgroup) {
if (thread)
thread->join();
}
m_threadgroup.clear();
}
std::list<std::shared_ptr<std::thread>> m_threadgroup;
SyncQueue<Task> m_queue;
atomic_bool m_running;
std::once_flag m_flag;
}; //=========================================================
void TestThdPool()
{
ThreadPool pool;
pool.Start(); std::thread thd1([&pool] {
for (int i = ; i < ; i++) {
auto thdId = this_thread::get_id();
pool.AddTask([thdId] {
std::cout << "thread1 id : " << thdId << std::endl;
});
}
}); std::thread thd2([&pool] {
for (int i = ; i < ; i++) {
auto thdId = this_thread::get_id();
pool.AddTask([thdId] {
std::cout << "thread2 id : " << thdId << std::endl;
});
}
}); this_thread::sleep_for(std::chrono::seconds());
getchar();
pool.Stop();
thd1.join();
thd2.join();
} int main()
{
TestThdPool();
return ;
}
ThreadPool.cpp
运行情况如下:
buffer area is empty,wait... threadID: 10244
buffer area is empty,wait... threadID: 8168
buffer area is empty,wait... threadID: 10136
buffer area is empty,wait... threadID: 5812
buffer area is empty,wait... threadID: 4064
buffer area is empty,wait... threadID: 7872
thread1 id : 9712buffer area is empty,wait... threadID:
8168
thread1 id : 9712
buffer area is empty,wait... threadID: 10244thread1 id : 9712
thread2 id : buffer area is empty,wait... threadID: thread2 id : 65206520
5812
thread2 id : thread1 id : thread2 id : 9712buffer area is empty,wait... threadID: thread2 id : 65206520
6520
thread2 id :
6520
thread2 id :
6520thread1 id :
40649712
thread2 id :
6520buffer area is empty,wait... threadID: thread2 id : 6520
thread1 id : 97125812
thread1 id : 9712buffer area is empty,wait... threadID: thread1 id : 10136
9712
buffer area is empty,wait... threadID: 7872thread1 id : 9712
thread2 id : 6520buffer area is empty,wait... threadID:
10244
thread1 id : 9712
buffer area is empty,wait... threadID: 8168
c++11 线程池学习笔记 (二) 线程池的更多相关文章
- JUC源码学习笔记5——线程池,FutureTask,Executor框架源码解析
JUC源码学习笔记5--线程池,FutureTask,Executor框架源码解析 源码基于JDK8 参考了美团技术博客 https://tech.meituan.com/2020/04/02/jav ...
- 操作系统学习笔记----进程/线程模型----Coursera课程笔记
操作系统学习笔记----进程/线程模型----Coursera课程笔记 进程/线程模型 0. 概述 0.1 进程模型 多道程序设计 进程的概念.进程控制块 进程状态及转换.进程队列 进程控制----进 ...
- java学习笔记15--多线程编程基础2
本文地址:http://www.cnblogs.com/archimedes/p/java-study-note15.html,转载请注明源地址. 线程的生命周期 1.线程的生命周期 线程从产生到消亡 ...
- JMX学习笔记(二)-Notification
Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...
- Linux内核学习笔记二——进程
Linux内核学习笔记二——进程 一 进程与线程 进程就是处于执行期的程序,包含了独立地址空间,多个执行线程等资源. 线程是进程中活动的对象,每个线程都拥有独立的程序计数器.进程栈和一组进程寄存器 ...
- muduo学习笔记(二)Reactor关键结构
目录 muduo学习笔记(二)Reactor关键结构 Reactor简述 什么是Reactor Reactor模型的优缺点 poll简述 poll使用样例 muduo Reactor关键结构 Chan ...
- python3.4学习笔记(二) 类型判断,异常处理,终止程序
python3.4学习笔记(二) 类型判断,异常处理,终止程序,实例代码: #idle中按F5可以运行代码 #引入外部模块 import xxx #random模块,randint(开始数,结束数) ...
- JDBC学习笔记二
JDBC学习笔记二 4.execute()方法执行SQL语句 execute几乎可以执行任何SQL语句,当execute执行过SQL语句之后会返回一个布尔类型的值,代表是否返回了ResultSet对象 ...
- Java IO学习笔记二
Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...
随机推荐
- Let'sencrypt.sh 抛出异常: Response: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:726)>
起因 今天网站的SSL证书过期了,打算重新申请,运行 Let'sencrypt.sh 的时候抛出了这么个异常. 一番搜索,发现居然找不到直接的答案.没有直接的答案就只能通过间接的答案来解决了. 希望我 ...
- Getting started - RN1
0. down yarn https://yarnpkg.com 1. Expo Cli 此环境用于开发或学习之用. (1)install npm install -g expo-cli (2) us ...
- Java 里面各种类型之间的相互转换
1.整形与字符型之间的数据类型转换: 一.int转换成char有两种方法: ① 是利用char的unicode编码 例:int num1 = 8; char ch1 = (char) (num1 + ...
- 用java打印图形
代码如下 public static void main(String[] args) { for (int i = 0; i <7; i++) { for (int j = 0; j < ...
- 统计uint64的数对应二进制数的1的个数
// pc[i] is the populatio count of ivar pc [256]byte //统计出o~255每个数对应二进制上1的个数func init() { for i ...
- JVM之堆内存(年经代,老年代)
一.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分代完全可以,分代的唯一理由就是优化GC性能.你先想想,如果没有分代,那我们所有的对象都在一块,GC的时候我 ...
- c/c++ 整数除预算保留小数
两个整数相除会自动省略小数点后的小数位即使下面这种: int a,int b; int a = 4; int b = 3; double d = a/b; d= 1.0000000; -------- ...
- 转 cxgrid属性说明
TCXGRID控件:属性:ActiveLevel: 当前层BorderStyle: 窗口风格Color: 颜色FocusedView: 当前View;Font: 字体LevelTabs: 类似Page ...
- 联想电脑t450,t460p,t470等安装好ubuntu后启动找不到系统
其实我是这样解决的: 进入bios: 关quick start 关security 然后reboot就可以了
- web.xml hello1代码分析
在“Web页”节点下,展开WEB-INF节点,然后双击web.xml文件进行查看. 上下文参数提供Web应用程序所需的配置信息.应用程序可以定义自己的上下文参数.此外,JavaServer Faces ...