线程是操作系统的一个概念。通常操作系统通过一组逻辑上关联的API函数实现对线程的操作。但是在面向对象编程中,C方式的API调用显然与其他的对象代码不符合。因此提供我的封装方法,简单有效,以Windows平台为例。 #pragma once#include <windows.h> class Thread{public: Thread(const char *name) : hThread(0), dwThread(0), bTerminated(false), pname(name){} ~Thread() { End(); } void Start() { if(hThread == 0) hThread = CreateThread(0,0, (LPTHREAD_START_ROUTINE)Thread::ThreadProc, this,0,&dwThread); bEnded = false; bTerminated = false; } void Suspend() { SuspendThread(hThread); } void Resume() { ResumeThread(hThread); } bool End() { if(bEnded) return true; bEnded = false; bTerminated = true; int count = 0; while( !bEnded && count++ < 10) Sleep(1000); if(!bEnded) { TerminateThread(hThread, (DWORD)-1); hThread = 0; return false; } hThread = 0; return true; } bool Ended() { if(bEnded) hThread = 0; return bEnded; } bool Wait() { while(!Ended()) Sleep(100); }protected: HANDLE hThread; DWORD dwThread; bool bTerminated; volatile bool bEnded; const char * pname; virtual bool Run() = 0; //具体的run操作通过继承实现。private: static unsigned ThreadProc(Thread *pThread) // 线程函数 { while( !pThread->bTerminated && pThread->Run() ) ; pThread->bEnded = true; return 0; }};

评论