windows下多线程类CThread
忘记在哪位仁兄那里得到了,还没有验证过。备用吧,或许以后还是要自己实现。
其实,编程也就是这样啦。最适合、最放心的往往都是自己实现的。
#include <windows.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; class CThread { public: CThread(); virtual DWORD Run(); bool Start(); bool Join(DWORD nMillSec = 200); private: static DWORD WINAPI RunThread(LPVOID pParam); HANDLE m_hThread; LPVOID m_pParam; DWORD m_nRet; bool m_bStart; }; CThread::CThread() { m_hThread = NULL; m_pParam = NULL; m_nRet = 0; m_bStart = false; } DWORD CThread::Run() { return 0; } bool CThread::Start() { m_bStart = true; m_hThread = CreateThread(NULL, 0, &RunThread, this, 0, NULL); if (!m_hThread) { m_bStart = false; return false; } return true; } bool CThread::Join(DWORD nMillSec) { while (m_bStart) Sleep(nMillSec); if (FALSE == GetExitCodeThread(m_hThread, &m_nRet)) return false; else { CloseHandle(m_hThread); return true; } } DWORD WINAPI CThread::RunThread(LPVOID pParam) { CThread* pThis = (CThread*)pParam; DWORD nRet = pThis->Run(); pThis->m_bStart = false; return nRet; } class MyThread : public CThread { public: DWORD Run(); }; DWORD MyThread::Run() { cout << "..." << endl; return 0; } int main(int argc, char **argv) { MyThread my; my.Start(); my.Join(); return 0; }
posted on 2014-01-02 12:40 xuejianhui 阅读(994) 评论(0) 编辑 收藏 举报