#include "CThreadPool.h" bool CThreadPool::Create(uint32_t nThreadCnt) { //创建信号量 m_hSemphore = CreateSemaphore(NULL, 0, MAXLONG, NULL); //check ... //创建线程 if (nThreadCnt == -1) { SYSTEM_INFO si; GetSystemInfo(&si); nThreadCnt = si.dwNumberOfProcessors; } m_bRunning = true; for (size_t i = 0; i < nThreadCnt; i++) { HANDLE hThread = CreateThread( NULL, // no security attributes 0, // use default stack size WorkThread, // thread function this, // argument to thread function 0, // use default creation flags NULL); // returns the thread identifier //check ... m_aryThreads.push_back(hThread); } return true; } bool CThreadPool::Destroy() { return false; } void CThreadPool::AddTask(ITask* pTask) { //添加任务 m_mtx.lock(); m_queTasks.push(pTask); m_mtx.unlock(); //释放信号 ReleaseSemaphore(m_hSemphore, 1, NULL); } DWORD __stdcall CThreadPool::WorkThread(LPVOID lpParameter) { CThreadPool* pThis = (CThreadPool*)lpParameter; while (pThis->m_bRunning) { //等待任务 WaitForSingleObject(pThis->m_hSemphore, INFINITE); //获取任务,执行 pThis->m_mtx.lock(); ITask* pTask = pThis->m_queTasks.front(); pThis->m_queTasks.pop();//出队 pThis->m_mtx.unlock(); pTask->ExcuteTask(); delete pTask; } return 0; }
#pragma once #include <queue> #include <mutex> #include <Windows.h> class ITask { public: virtual void ExcuteTask() = 0; }; class CThreadPool { public: bool Create(uint32_t nThreadCnt = -1); bool Destroy(); void AddTask(ITask* pTask); private: std::queue<ITask*> m_queTasks; //任务队列 std::recursive_mutex m_mtx; HANDLE m_hSemphore{}; //信号量 std::vector<HANDLE> m_aryThreads; //线程 bool m_bRunning{false}; static DWORD WINAPI WorkThread(LPVOID lpParameter); };
标签:mtx,pTask,CThreadPool,线程,nThreadCnt,pThis,NULL From: https://www.cnblogs.com/yewu1/p/17338613.html