微软提供了一套线程池的API,但是直接使用比较费劲,前段时间用的时候做了简单的封装,现记录于此方便以后使用。
头文件:
#pragma once class CMyThreadPool { public: CMyThreadPool(); ~CMyThreadPool(); public: bool StartNewWork(PTP_WORK_CALLBACK workcallback, PVOID pParam); private: BOOL InitThreadPool(); void UninitTreadPool(); private: PTP_POOL m_threadPool; TP_CALLBACK_ENVIRON m_callBackEnviron; PTP_CLEANUP_GROUP m_cleanupgroup; };
cpp文件:
#include "StdAfx.h" #include "MyThreadPool.h" CMyThreadPool::CMyThreadPool(void): m_threadPool(NULL), m_cleanupgroup(NULL) { } CMyThreadPool::~CMyThreadPool(void) { UninitTreadPool(); } bool CMyThreadPool::StartNewWork(PTP_WORK_CALLBACK workcallback, PVOID pParam) { if (!InitThreadPool()) { return false; } PTP_WORK new_work = CreateThreadpoolWork(workcallback , pParam , &m_callBackEnviron); bool bResult = false; if (NULL != new_work) { SubmitThreadpoolWork(new_work); bResult = true; } return bResult; } BOOL CMyThreadPool::InitThreadPool() { if (NULL == m_threadPool) { InitializeThreadpoolEnvironment(&m_callBackEnviron); m_threadPool = ::CreateThreadpool(NULL); if (NULL == m_threadPool) { return FALSE; } SetThreadpoolThreadMaximum(m_threadPool, 5); if (!SetThreadpoolThreadMinimum(m_threadPool, 1)) { CloseThreadpool(m_threadPool); m_threadPool = NULL; return FALSE; } m_cleanupgroup = CreateThreadpoolCleanupGroup(); if (NULL == m_cleanupgroup) { CloseThreadpool(m_threadPool); m_threadPool = NULL; return FALSE; } SetThreadpoolCallbackPool(&m_callBackEnviron, m_threadPool); SetThreadpoolCallbackCleanupGroup(&m_callBackEnviron, m_cleanupgroup, NULL); } return TRUE; } void CMyThreadPool::UninitTreadPool() { if (NULL != m_cleanupgroup) { CloseThreadpoolCleanupGroupMembers(m_cleanupgroup, FALSE, NULL); CloseThreadpoolCleanupGroup(m_cleanupgroup); m_cleanupgroup = NULL; } if (NULL != m_threadPool) { CloseThreadpool(m_threadPool); m_threadPool = NULL; } }
使用的时候只需要实例化一个CMyThreadPool对象,然后调用StartNewWork方法即可。
注意:上面用的API只有在Vista以上的版本才支持,XP不支持。