// Test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> #include <process.h> #include <vector> typedef unsigned (__stdcall*LP_THREAD_FUN)(void*); class Thread{ public: Thread(){ m_fun = NULL; m_param = NULL; m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, this, CREATE_SUSPENDED, NULL); printf("Thread Create: %08X\n", m_hThread); } ~Thread(){ Terminate(); CloseHandle(m_hThread); } void SetThreadFun(LP_THREAD_FUN fun, void* param){ m_fun = fun; m_param = param; } void Start(){ DWORD dwCount = ResumeThread(m_hThread); if (dwCount == -1){ printf("ResumeThread Fail, LastError: %d", GetLastError()); } } void Pause(){ DWORD dwCount = SuspendThread(m_hThread); if (dwCount == -1){ printf("SuspendThread Fail, LastError: %d", GetLastError()); } } void Resume(){ DWORD dwCount = ResumeThread(m_hThread); if (dwCount == -1){ printf("ResumeThread Fail, LastError: %d", GetLastError()); } } void Terminate(){ if (!TerminateThread(m_hThread, 0)){ printf("TerminateThread Fail, LastError: %d", GetLastError()); } } protected: static unsigned __stdcall ThreadFun(void* param){ Thread* p = (Thread*)param; if (p && p->m_fun) { p->m_fun(p->m_param); } return 0; } HANDLE m_hThread; LP_THREAD_FUN m_fun; void* m_param; }; class ThreadPool{ public: ThreadPool(): m_iAvailableIndex(0){} ~ThreadPool(){ std::vector<Thread*>::iterator ita = m_vecThread.begin(); while (ita != m_vecThread.end()){ delete (Thread*)(*ita); ita++; } m_vecThread.clear(); } void Init(int threadcount){ m_vecThread.resize(threadcount); for (int i = 0; i < threadcount; ++i){ m_vecThread[i] = new Thread; } } Thread* GetAvailabelThread(){ if (m_iAvailableIndex < m_vecThread.size()){ return m_vecThread[m_iAvailableIndex++]; } return NULL; } protected: std::vector<Thread*> m_vecThread; int m_iAvailableIndex; }; unsigned __stdcall TestFun(void* p) { printf("TestFun: %d", p); return 0; } int _tmain(int argc, _TCHAR* argv[]) { ThreadPool pool; int count = 0; printf("Please input thread count: "); scanf("%d", &count); pool.Init(count); Thread* p = pool.GetAvailabelThread(); if (p) { printf("Please input scedule thread: "); scanf("%d", &count); p->SetThreadFun(TestFun, (void*)count); printf("Run thread: "); scanf("%d", &count); p->Start(); } system("@pause"); return 0; }
时间: 2024-11-08 01:15:47