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