简单封装一下 win内核线程池 以后直接继承 不用复写

#pragma  once
#include <windows.h>
#include <iostream>

class MyThreadPoll
{
public:
	MyThreadPoll();
	virtual~MyThreadPoll();

	void InitThreadAndEnviron(unsigned int minNum = 1, unsigned int maxNum = 500);
	
	void CleanThreadAndEnviron();

	bool isThreadPoolInit(){ return _isThreadPoolInit; }
	bool PushThread(
		VOID(NTAPI *Func)
		(
		 PTP_CALLBACK_INSTANCE Instance,
		 PVOID                 Context
		) = NULL, void *param = NULL);
	
	void  SetThreadRunsLong();
	
	void SetThreadCallLibrary(void *param);
	
protected:
	bool _isThreadPoolInit;
	PTP_POOL _pool;
	PTP_CALLBACK_ENVIRON _environ;
};
MyThreadPoll::MyThreadPoll() :_pool(0), _environ(0), _isThreadPoolInit(0){}
MyThreadPoll::~MyThreadPoll()
{
	if (_isThreadPoolInit)
		CleanThreadAndEnviron();
}

void MyThreadPoll::InitThreadAndEnviron(unsigned int minNum /*= 1*/, unsigned int maxNum /*= 500*/)
{
	if (!_isThreadPoolInit)
	{
		_pool = CreateThreadpool(0);
		_environ = new TP_CALLBACK_ENVIRON();
		SetThreadpoolThreadMinimum(_pool, minNum);
		SetThreadpoolThreadMaximum(_pool, maxNum);
		InitializeThreadpoolEnvironment(_environ);
		//开始绑定
		SetThreadpoolCallbackPool(_environ, _pool);
		_isThreadPoolInit = !_isThreadPoolInit;
	}
}

void MyThreadPoll::CleanThreadAndEnviron()
{
	if (_isThreadPoolInit)
	{
		DestroyThreadpoolEnvironment(_environ);//清理线程环境
		CloseThreadpool(_pool);//关闭线程
		_pool = NULL;
		delete _environ;
		_environ = NULL;
		_isThreadPoolInit = !_isThreadPoolInit;
	}
}

bool MyThreadPoll::PushThread(VOID(NTAPI *Func) ( PTP_CALLBACK_INSTANCE Instance, PVOID Context) /*= NULL*/, void *param /*= NULL*/)
{
	if (!Func)
		return false;
	TrySubmitThreadpoolCallback(Func, param, _environ);
	return true;
}

void MyThreadPoll::SetThreadRunsLong()
{
	if (_environ)
		SetThreadpoolCallbackRunsLong(_environ);
}

void MyThreadPoll::SetThreadCallLibrary(void *param)
{
	if (param == NULL)
		return;
	if (_environ)
		SetThreadpoolCallbackLibrary(_environ, param);
}

这当然是一部分封装 还有 工作者 io time 等等 原则差不多  就不贴出来了 

以后写 IO  Sock时 或文件 时 直接继承 节省不事  可谓轻松加愉快

你可能感兴趣的:(简单封装一下 win内核线程池 以后直接继承 不用复写)