学习内容来自以下地址

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 线程池学习笔记 (二) 线程池的更多相关文章

  1. JUC源码学习笔记5——线程池,FutureTask,Executor框架源码解析

    JUC源码学习笔记5--线程池,FutureTask,Executor框架源码解析 源码基于JDK8 参考了美团技术博客 https://tech.meituan.com/2020/04/02/jav ...

  2. 操作系统学习笔记----进程/线程模型----Coursera课程笔记

    操作系统学习笔记----进程/线程模型----Coursera课程笔记 进程/线程模型 0. 概述 0.1 进程模型 多道程序设计 进程的概念.进程控制块 进程状态及转换.进程队列 进程控制----进 ...

  3. java学习笔记15--多线程编程基础2

    本文地址:http://www.cnblogs.com/archimedes/p/java-study-note15.html,转载请注明源地址. 线程的生命周期 1.线程的生命周期 线程从产生到消亡 ...

  4. JMX学习笔记(二)-Notification

    Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...

  5. Linux内核学习笔记二——进程

    Linux内核学习笔记二——进程   一 进程与线程 进程就是处于执行期的程序,包含了独立地址空间,多个执行线程等资源. 线程是进程中活动的对象,每个线程都拥有独立的程序计数器.进程栈和一组进程寄存器 ...

  6. muduo学习笔记(二)Reactor关键结构

    目录 muduo学习笔记(二)Reactor关键结构 Reactor简述 什么是Reactor Reactor模型的优缺点 poll简述 poll使用样例 muduo Reactor关键结构 Chan ...

  7. python3.4学习笔记(二) 类型判断,异常处理,终止程序

    python3.4学习笔记(二) 类型判断,异常处理,终止程序,实例代码: #idle中按F5可以运行代码 #引入外部模块 import xxx #random模块,randint(开始数,结束数) ...

  8. JDBC学习笔记二

    JDBC学习笔记二 4.execute()方法执行SQL语句 execute几乎可以执行任何SQL语句,当execute执行过SQL语句之后会返回一个布尔类型的值,代表是否返回了ResultSet对象 ...

  9. Java IO学习笔记二

    Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...

随机推荐

  1. dapper List SqlBulkCopy

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  2. 链表(list)使用注意

    如下代码是linux上的链表接口源码,使用的这个链表(list)源码,可以方便快捷的建立链表队列,但使用时需要注意的坑有: 1.不支持,多对多,否则在add的时候,因为要加入链表的对象只有一块list ...

  3. MOBA英雄AI设计分享

    转自:http://www.gamelook.com.cn/2018/07/333877 文/wataloo 1  设计概要 1.1  设计原则和目的 英雄AI的目的主要有: 1.新手过渡局,让玩家刚 ...

  4. C#委托防止事件多次注册

    示例代码如下: class NodeInf { public delegate void mydelegate(ProcessContent processContent); private myde ...

  5. postgresql数据库备份

    一.工具备份数据 打开windows下的命令窗口:开始->cmd->安装数据库的目录->进入bin目录: 导出命令:pg_dump –h localhost –U postgres ...

  6. 游戏中转盘概率的算法---python实现

    加入转盘的内容及概率如下 转盘倍数 0.5 0.6 0.7 0.8 1 1.2 1.5 1.8 2 机率 0.2 0.15 0.15 0.2 0.2 0.1 0.1 0.05 0.05 下面来实现转盘 ...

  7. idea本地跑代码和链接开发机设置

  8. Android开发 assets目录

    Android资源文件分类: Android资源文件大致可以分为两种: 第一种是res目录下存放的可编译的资源文件: 这种资源文件系统会在R.Java里面自动生成该资源文件的ID,所以访问这种资源文件 ...

  9. 实战ELK(7)ElasticSearch常用的基本查询语句

    1.term 过滤 term主要用于精确匹配哪些值,比如数字,日期,布尔值或 not_analyzed 的字符串(未经切词的文本数据类型): { "term": { "d ...

  10. 代码: 两列图片瀑布流(一次后台取数据,图片懒加载。下拉后分批显示图片。图片高度未知,当图片onload后才显示容器)

    代码: 两列图片瀑布流(一次后台取数据,无ajax,图片懒加载.下拉后分批显示图片.图片高度未知,当图片onload后才显示容器) [思路]: 图片瀑布流,网上代码有多种实现方式,也有各类插件.没找到 ...