简单的线程类

来源:互联网 发布:js获取ip地址 编辑:程序博客网 时间:2024/06/08 02:26

本着代码大家分享的精神,将改了又改的线程类发布于此。

//--------------------------------------------------------------////Copyright (C) 2009 - All Rights Reserved.////Author:LiuYin//File:Thread//Version: 1.0//Date: 2009-8-10////Purpose:////--------------------------------------------------------------#ifndef Thread_H#define Thread_H//////////////////////////////////////////////////////////////////////////#include <WTypes.h>#include <Process.h>//////////////////////////////////////////////////////////////////////////template <DWORD dwUnique>class ThreadT{typedef ThreadT<dwUnique> This;//////////////////////////////////////////////////////////////////////////public:typedef DWORD (WINAPI *ThreadRoutineT)(LPVOID lpParam, HANDLE hEventExit);private:struct ThreadParam{This *pThis;LONG lCount;HANDLE hStart;ThreadRoutineT threadRoutine;LPVOID lpParam;};//////////////////////////////////////////////////////////////////////////public:ThreadT():m_lThreadCount(0){m_hEventExit = ::CreateEvent(NULL, TRUE, FALSE, NULL);m_hEventWait = ::CreateEvent(NULL, TRUE, FALSE, NULL);}~ThreadT(){if (m_hEventWait != NULL) {::CloseHandle(m_hEventWait);m_hEventWait = NULL;}if (m_hEventExit != NULL) {::CloseHandle(m_hEventExit);m_hEventExit = NULL;}}LONG GetThreadCount() const{return m_lThreadCount;}DWORD Start(ThreadRoutineT threadRoutine, LPVOID lpParam, DWORD dwCount){if ((threadRoutine == NULL) && (dwCount == 0)) {return ERROR_INVALID_PARAMETER;}ThreadParam threadParam = { 0 };threadParam.pThis= this;threadParam.lCount= (LONG) dwCount;threadParam.hStart= ::CreateEvent(NULL, TRUE, FALSE, NULL);threadParam.threadRoutine= threadRoutine;threadParam.lpParam= lpParam;for (DWORD i=0; i<dwCount; ++i) {::CloseHandle((HANDLE) _beginthreadex(NULL, 0, ThreadT::_SvcBase, &threadParam, 0, NULL));}::WaitForSingleObject(threadParam.hStart, INFINITE);::CloseHandle(threadParam.hStart);threadParam.hStart = NULL;return ERROR_SUCCESS;}VOID Stop(){if (m_lThreadCount > 0) {::SetEvent(m_hEventExit);::WaitForSingleObject(m_hEventWait, INFINITE);::ResetEvent(m_hEventExit);::ResetEvent(m_hEventWait);}}private:static unsigned __stdcall _SvcBase(LPVOID pParam){ThreadParam *pThreadParam = static_cast<ThreadParam *>(pParam);pThreadParam->pThis->Svc(pThreadParam);return 0xDEAD;}VOID Svc(ThreadParam *pThreadParam){ThreadRoutineT threadRoutine = pThreadParam->threadRoutine;LPVOID lpParam = pThreadParam->lpParam;InterlockedIncrement(&m_lThreadCount);if (InterlockedDecrement(&(pThreadParam->lCount)) == 0) {::SetEvent(pThreadParam->hStart);}threadRoutine(lpParam, m_hEventExit);if (InterlockedDecrement(&m_lThreadCount) == 0) {::SetEvent(m_hEventWait);}}private:volatile LONG m_lThreadCount;HANDLE m_hEventWait;HANDLE m_hEventExit;};//////////////////////////////////////////////////////////////////////////typedef ThreadT<0> CThread;//////////////////////////////////////////////////////////////////////////#endif 


0 0