学习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