#ifndef THREAD_POOL_H
#define THREAD_POOL_H #include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept> class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks; // synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
}; // the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task; {
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();
} task();
}
}
);
} // add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
); 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();
return res;
} // the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
} #endif

学习c++11 ThreadPool【转】的更多相关文章

  1. Ext.Net学习笔记11:Ext.Net GridPanel的用法

    Ext.Net学习笔记11:Ext.Net GridPanel的用法 GridPanel是用来显示数据的表格,与ASP.NET中的GridView类似. GridPanel用法 直接看代码: < ...

  2. SQL反模式学习笔记11 限定列的有效值

    目标:限定列的有效值,将一列的有效字段值约束在一个固定的集合中.类似于数据字典. 反模式:在列定义上指定可选值 1. 对某一列定义一个检查约束项,这个约束不允许往列中插入或者更新任何会导致约束失败的值 ...

  3. golang学习笔记11 golang要用jetbrain的golang这个IDE工具开发才好

    golang学习笔记11   golang要用jetbrain的golang这个IDE工具开发才好  jetbrain家的全套ide都很好用,一定要dark背景风格才装B   从File-->s ...

  4. Spring MVC 学习笔记11 —— 后端返回json格式数据

    Spring MVC 学习笔记11 -- 后端返回json格式数据 我们常常听说json数据,首先,什么是json数据,总结起来,有以下几点: 1. JSON的全称是"JavaScript ...

  5. Python3+Selenium3+webdriver学习笔记11(cookie处理)

    #!/usr/bin/env python# -*- coding:utf-8 -*-'''Selenium3+webdriver学习笔记11(cookie处理)'''from selenium im ...

  6. 并发编程学习笔记(11)----FutureTask的使用及实现

    1. Future的使用 Future模式解决的问题是.在实际的运用场景中,可能某一个任务执行起来非常耗时,如果我们线程一直等着该任务执行完成再去执行其他的代码,就会损耗很大的性能,而Future接口 ...

  7. 《C++ Primer Plus》学习笔记11

    <C++ Primer Plus>学习笔记11 第17章 输入.输出和文件 <<<<<<<<<<<<<< ...

  8. SpringMVC:学习笔记(11)——依赖注入与@Autowired

    SpringMVC:学习笔记(11)——依赖注入与@Autowired 使用@Autowired 从Spring2.5开始,它引入了一种全新的依赖注入方式,即通过@Autowired注解.这个注解允许 ...

  9. 零基础学习前端1-1配置node及npm环境变量

    零基础学习前端1-1配置node及npm环境变量 ## 1-1配置node及npm环境变量 首先:下载node 可以直接去官方网站下载 1.首先从官网下载安装包 https://nodejs.org/ ...

随机推荐

  1. EF Core 实现读写分离的最佳方案

    前言 公司之前使用Ado.net和Dapper进行数据访问层的操作, 进行读写分离也比较简单, 只要使用对应的数据库连接字符串即可. 而最近要迁移到新系统中,新系统使用.net core和EF Cor ...

  2. mybatis执行过程及经典面试题

    Mybatis执行流程 mybatis中xml解析是通过SqlSessionFactoryBuilder.build()方法. 初始化mybatis(解析xml文件构建成Configuration对象 ...

  3. PCIE DMA实现

    基于Spartan-6, Virtex-5/Virtex-6/Virtex-7/7 Series FPGA PCI Express Block Endpoint模块设计PCI Express Endp ...

  4. MySQL 5.7安装最佳实践

    MySQL 5.7安装最佳实践 1.环境准备OS: CentOS Linux release 7.4.1708 (Core) for VMwareMySQL: mysql-5.7.24-linux-g ...

  5. eclipse中的项目运行时不出现run as→java application选项

    eclipse中的运行java project时不出现run as→java application选项? 解决方案☞必须有正确的主方法,即public static void main(String ...

  6. 后渗透神器Cobalt Strike的安装

    0x01 简介 Cobalt Strike集成了端口转发.扫描多模式端口监听Windows exe木马,生成Windows dll(动态链接库)木马,生成java木马,生成office宏病毒,生成木马 ...

  7. Python开发【第六篇】循环语句

    while 语句 注意事项:1.要控制循环的真值表达式的值来防止死循环 ​ 2.通常用真值表达式内的循环变量来控制循环条件 ​ 3.通常在语句内部改变循环变量 ​ 4.只要是语句都可以互相嵌套 whi ...

  8. Pathon中numpy模块

    目录 numpy模块 切割矩阵 矩阵元素替换 矩阵的合并 通过函数创建矩阵 fromstring/fromfunctions 矩阵的运算 常用矩阵运函数 矩阵的点乘 矩阵的逆 矩阵的其他操作 nump ...

  9. 《Java并发编程实战》读书笔记-第一部分 基础知识小结

    并发技巧清单 可变状态是至关重要的 所有的并发问题都可以归结为如何协调对并发状态的访问.可变状态越少,就越容易确保线程安全性. 尽量将域声明为final类型,除非需要它们是可变的. 不可变对象一定是线 ...

  10. POJ 1258 Agri-Net(Prim)

    题目网址:http://poj.org/problem?id=1258 题目: Agri-Net Time Limit: 1000MS   Memory Limit: 10000K Total Sub ...