自定义c++线程池
来源:互联网 发布:淘宝钻展怎么弄啊 编辑:程序博客网 时间:2024/05/19 22:44
学习c++有一段时间了,打算从string、线程池、网络等方面入手,写一些东西。期间参考了网络上很多书写线程池的blog。以为是很简单的事,真正着手编程调试的时候确遇到了很多的问题。如:
1)两个类的头文件交叉引用,导致编译通不过的问题。解决方案:抽取出父类,通过继承,解决这个问题。
2) new出来的对象在回收的时候,引发的一些异常。
3)如何保证线程在对象销毁之前回收。解决方案:在析构函数中,写一个带睡眠的死循环。直到线程结束后,退出循环。
通过一系列的优化后,将线程池的核心功能都实现了,却发现类分的太细,不利于排查问题,感觉不是最好的实现方案。最后在综合权衡之后,将线程池改造如下。
#pragma once#include<queue>#include<thread>#include<mutex>#include<condition_variable>#include<iostream>using namespace std;class Thread{public:typedef void (*TheadFuncion)();thread* th = nullptr;void* data;TheadFuncion func;bool exit = false;bool isExitSuccess = false;bool idle = true;bool isHasTask = false;void Func(){isExitSuccess = false;while (!exit) {if (isHasTask) {isHasTask = false;this->func();idle = true;}else {chrono::milliseconds(40);}}isExitSuccess = true;}bool Start(Thread::TheadFuncion func){if (!idle) {return false;}idle = false;this->func = func;isHasTask = true;if (nullptr == th) {th = new thread([&]() {Func();});th->detach();}return true;}bool IsIdle() {return idle;}void Stop(){exit = true;while (!isExitSuccess) {chrono::milliseconds(40);}cout << "stop<<" << th << ">>" << endl;delete th;}Thread(){}~Thread(){if (nullptr == th) {exit = true;}else {if (!exit) {Stop();}}}};class ThreadPool1{public:vector<Thread*> threads; typedef std::vector<Thread*>::iterator Iterator; mutex mtx; bool isEnd = false;public:ThreadPool1(int threadCount){for (int i = 0; i < threadCount; i++) {Thread* thread = new Thread();threads.push_back(thread);}}~ThreadPool1() {Iterator iter = threads.begin();while (iter != threads.end()) {if (nullptr != *iter) {delete *iter;}iter++;}isEnd = true;}void start() {}bool Add(Thread::TheadFuncion func){mtx.lock();Iterator iter = threads.begin();bool isAddSuccess = false;while (iter != threads.end()) {if ((*iter) -> IsIdle()) {isAddSuccess = (*iter)->Start(func);if (isAddSuccess) {break;}else {iter++;}}else {iter++;}}mtx.unlock();return isAddSuccess;}};
参考链接:http://www.cnblogs.com/haippy/p/3237213.html
阅读全文
0 0
- 自定义线程池(1)
- 自定义线程池(2)
- 自定义线程池(3)
- 自定义线程池代码
- 自定义线程池ThreadPool
- C# 自定义线程池
- 自定义线程池
- java自定义线程池
- java 自定义线程池
- 自定义java 线程池
- 自定义线程池ThreadPoolExecutor
- Android 自定义线程池
- 自定义线程池Executors
- python自定义线程池
- 自定义Java线程池
- 自定义c++线程池
- 自定义线程池
- 自定义线程池---ThreadPoolExecutor
- C语言-将1到9这九个数字分成三个3位数,要求第一个3位数,正好是第二个3位数的1/2,是第三个3位数的1/3。问应当怎样分,编写程序实现。
- c# sspi authentication
- 基于Lua的游戏服务端框架简介
- 02 JS-DOM之--js的加载和window onload
- angular2 form
- 自定义c++线程池
- /Proc/详解
- Quartus II的使用方法:以暑期硬件作业为例
- 进度条(shell)
- Calendar日历类和GregorianCalendar公历类的使用
- mysql 使用sum()函数时的一个小坑
- while 死循环
- Oracle快速入门002
- 机器学习实战之线性回归+局部加权线性回归