自定义c++线程池

本文分享了作者在使用C++开发线程池过程中的实践经验,包括解决类间头文件交叉引用、内存管理异常及确保线程正确回收等问题的方法,并最终提供了一个简洁高效的线程池实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值