使用QueueUserWorkerItem实现的线程池封装

          此线程池所依赖的线程类,请参看《一个Windows C++的线程类实现》

头文件:

// CThreadPool.h: interface for the CThreadPool class.
//
//////////////////////////////////////////////////////////////////////

#ifndef __C_PLUS_CTHREADPOOL_HEADER
#define __C_PLUS_CTHREADPOOL_HEADER

#include <windows.h>
#include <list>
#include "CThread.h"

using namespace std;

typedef std::list<Runnable*> Tasks;
typedef Tasks::iterator TaskIter;	

class CThreadPool  
{
public:
	CThreadPool();
	~CThreadPool();

	// 初始化线程池,创建maxTasks个线程
	BOOL Init(unsigned int maxTasks);

	// 执行任务,若当前任务列表没满,则将此任务加入到任务列表,返回TRUE
	BOOL Execute(Runnable* pRunnable);

	// 终止线程池,先制止塞入列表
	// 然后等待直到任务列表为空
	// 然后设置最小线程数量为0
	// 等待直到线程数量为空
	// 清空垃圾堆中的任务
	void Terminate();
	
	// 返回线程池中当前的线程数量
	unsigned int GetThreadSize();

public:
	Tasks m_Tasks;
	CRITICAL_SECTION m_csTaskLock;

private:
	static unsigned int WINAPI StaticThreadFunc(void* arg);

private:

	volatile BOOL m_bRun;
	volatile BOOL m_bEnableInsertTask;
	volatile unsigned int m_maxTasks;
};

#endif 
CPP文件:

// CThreadPool.cpp: implementation of the CThreadPool class.
//
//////////////////////////////////////////////////////////////////////

#include "CThreadPool.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CThreadPool::CThreadPool():m_bRun(FALSE), m_bEnableInsertTask(FALSE)
{
	InitializeCriticalSection(&m_csTaskLock);
}

CThreadPool::~CThreadPool()
{
	Terminate();
	DeleteCriticalSection(&m_csTaskLock);
}

BOOL CThreadPool::Init(unsigned int maxTasks)
{
	if ( maxTasks==0)
	{
		return FALSE;
	}

	m_maxTasks = maxTasks;
	m_bRun = TRUE;
	m_bEnableInsertTask = TRUE;
	return TRUE;	
}

BOOL CThreadPool::Execute(Runnable* pRunnable)
{
	if (!m_bEnableInsertTask)
	{
		return FALSE;
	}

	if (NULL == pRunnable)
	{
		return FALSE;
	}

	EnterCriticalSection(&m_csTaskLock);

	if (m_Tasks.size()>=m_maxTasks)
	{
		LeaveCriticalSection(&m_csTaskLock);
		return FALSE;
	}

	m_Tasks.push_back(pRunnable);
	LeaveCriticalSection(&m_csTaskLock);

	BOOL bRet = QueueUserWorkItem((LPTHREAD_START_ROUTINE)StaticThreadFunc, this, WT_EXECUTEINPERSISTENTIOTHREAD);

	if( bRet)
	{
		EnterCriticalSection(&m_csTaskLock);
		m_Tasks.remove(pRunnable);
		LeaveCriticalSection(&m_csTaskLock);
	}
	return bRet;	
}

unsigned int CThreadPool::GetThreadSize()
{
	return m_Tasks.size();
}

void CThreadPool::Terminate()
{
	m_bEnableInsertTask = FALSE;
	m_bRun = FALSE;
	while (m_Tasks.size()!=0)
	{
		Sleep(1);
	}	
}

unsigned int WINAPI CThreadPool::StaticThreadFunc(void* arg)
{
	CThreadPool* pThreadPool = (CThreadPool*)arg;
	
	Runnable* pRunnable = NULL;
	EnterCriticalSection(&pThreadPool->m_csTaskLock);
	pRunnable = pThreadPool->m_Tasks.front();

	if ( NULL !=pRunnable)
	{
		pThreadPool->m_Tasks.pop_front();
	}
	LeaveCriticalSection(&pThreadPool->m_csTaskLock);

	if ( NULL !=pRunnable)
	{
		pRunnable->Run();
	}
	
	return 0;
}



你可能感兴趣的:(线程池)