也可参考:  https://www.cnblogs.com/ailumiyana/p/10016965.html  ***
https://blog.csdn.net/jlusuoya/article/details/74505558  ***
 https://www.cnblogs.com/magicsoar/p/3788180.html  *****
 
//nocopyable类,不可拷贝基类继承它,派生类不可拷贝
//nocopyable.h
#ifndef NOCOPYABLE_H
#define NOCOPYABLE_H
 
namespace fivestar
{
  class nocopyable
  {
  private:
      nocopyable(const nocopyable& x) = delete;
      nocopyable& operator=(const nocopyable&x) = delete;
  public:
      nocopyable() = default;
      ~nocopyable() = default;
  };
 
}
 
#endif // NOCOPYABLE_H
 
//ThreadPool.h
#ifndef THREADPOOL_H
#define THREADPOOL_H
 
#include <thread>
#include <mutex>
#include <functional>
#include <string>
#include <condition_variable>
#include <deque>
#include <vector>
#include <memory>
 
#include "nocopyable.h"
namespace fivestar
{
  class ThreadPool:public nocopyable
  {
  public:
      typedef std::function<void()> Task;
 
      explicit ThreadPool(const std::string &name = std::string());
      ~ThreadPool();
 
 
      void start(int numThreads);//设置线程数,创建numThreads个线程
      void stop();//线程池结束
      void run(const Task& f);//任务f在线程池中运行
      void setMaxQueueSize(int maxSize) { _maxQueueSize = maxSize; }//设置任务队列可存放最大任务数
 
private:
      bool isFull();//任务队列是否已满
      void runInThread();//线程池中每个thread执行的function
      Task take();//从任务队列中取出一个任务
 
      std::mutex _mutex;
      std::condition_variable _notEmpty;
      std::condition_variable _notFull;
      std::string _name;
      std::vector<std::thread> _threads;
      std::deque<Task> _queue;
      size_t _maxQueueSize;
      bool _running;
  };
}
 
#endif // THREADPOOL_H
 
 

注意:

1 .为线程池添加任务之前一定要调用setMaxQueueSize,设置任务队列可存放的最大任务数,否则线程池退化为单线程

2 若不调用start创建线程,则线程池退化为单线程

测试代码

#include <iostream>
#include "ThreadPool.h"
 
using namespace std;
 
void Test(int i)
{
    printf("I love you %d time\n",i);
}
 
int main()
{
    fivestar::ThreadPool threadPool;
    threadPool.setMaxQueueSize(10);
    threadPool.start(2);
 
    for(int i = 0;i < 10;++i)
    {
        auto task = bind(Test,i);
        threadPool.run(task);
    }
 
    getchar();
    return 0;
}
 
 
 
 

最新文章

  1. Android之AnimationDrawable初识
  2. Hibernate学习-在线书城后台管理系统的设计
  3. 后一个div无法遮挡住前一个有img的div
  4. IOS版本被拒的经历
  5. 在安装ISE的情况下,充分利用ISE的安装目录,查找资料
  6. many-to-one和one-to-many的配置比较
  7. C语言数据结构之栈:括号匹配
  8. Mysql主从复制,读写分离
  9. Java基础知识强化42:StringBuffer类之StringBuffer的截取功能
  10. 手算KMP匹配的Next值和Nextval值
  11. Python基本语法[二],python入门到精通[四] (转)
  12. close()方法应该在finally语句中调用吗?
  13. 使用cookie来做身份认证
  14. kerberos环境下spark消费kafka写入到Hbase
  15. 【mysql】 快速搞定数据库迁移
  16. scrapy 第一个案例(爬取腾讯招聘职位信息)
  17. http/ftp等的URL匹配正则表达式 ZT
  18. 机器学习:K-近邻算法
  19. Echarts饼图更改颜色、显示数据且换行
  20. 20172325 2017-2018-2 《Java程序设计》第六周学习总结

热门文章

  1. prometheus 配置容器 cadvisor监控节点
  2. tensorflow 模型保存和加载
  3. Python“函数式编程”中常用的函数
  4. Django之Xadmin
  5. pt-online-schema-change VS oak-online-alter-table【转】
  6. 新闻API接口
  7. VMware虚拟机安装Linux后忘记root密码怎么办(三)
  8. PHP 必知的 16 个编程法则
  9. day13-迭代器及生成器
  10. 团队项目——NABCD